Leaflet: how to swap coordinates received from an ajax call

大兔子大兔子 提交于 2020-06-25 07:08:35

问题


I am using Leaflet 1.0.3 and a few plugins including Leaflet.ajax. My L.geo.ajax call is working and returning geojson objects, however, the coordinates are reversed. I created a function to fix this:

    var convertLatLng = function (latlng) {
    var temp = latlng[y];
    latlng[y] = latlng[x];
    latlng[x] = temp;
    convertedLatLng = latlng;
    return convertedLatLng;
    console.log('this function is running')
    }

But my problem is I don't know where to put it. Do I run it inside my geoJson call? If so, where? Here is a snippet of the ajax call:

    var geojson = L.geoJson.ajax('http://www.iotwf.com/deployment_map/json', {

    pointToLayer: function (feature, latlng) {
    convertLatLng(latlng);
    ...
    },
    onEachFeature: function(feature, layer) {
 
    ...
    }
    });

I am also open to other suggestions for what may fix it.


回答1:


Welcome to SO!

First make sure that your coordinates are indeed reversed.

Note that the GeoJSON format expects [longitude, latitude], whereas Leaflet usually expects [latitude, longitude], EXCEPT in the case of L.geoJSON() factory (and the plugin L.geoJson.ajax()), where it automatically reads the GeoJSON order and builds the layers at the correct coordinates.

If your coordinates are still reversed, the appropriate correction would be obviously to correct the order in your data source directly (or whatever service outputs your data), so that you get actually compliant GeoJSON data. That would solve many future headaches.

If that is not possible, then indeed you could try a workaround within your script.

The most appropriate way to do so would probably be to use the coordsToLatLng option of the L.geoJSON factory.

Changing its default implementation, you would get something like:

L.geoJson.ajax(url, {
    coordsToLatLng: function (coords) {
        //                    latitude , longitude, altitude
        //return new L.LatLng(coords[1], coords[0], coords[2]); //Normal behavior
        return new L.LatLng(coords[0], coords[1], coords[2]);
    }
});


来源:https://stackoverflow.com/questions/43549199/leaflet-how-to-swap-coordinates-received-from-an-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!