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.
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]);
}
});