How can I automatically center the map view on the drawn GeoJSON?
My GeoJSON can either contain a polygon or multiPolygon feature. I'm drawing the following GeoJSON onto my Leaflet map:
let parsedJson = JSON.parse(myString.geoJson);
let geoJSON = L.geoJson(parsedJson, {
...
}).addTo(myMap)
I tried fitBounds
on the map object, but both center the map out of bounds. Zoom: I'd like to set the view to the bounds of my polygons.
Edit: I realized, the coordinates returned by getCenter()
are for example LatLng(175.836357, -36.649876)
. When I switch them to LatLng(-36.649876, 175.836357)
the center point is correctly drawn.
If I'm not mistaken, LatLong ranges are:
North (+90)
|
(-180) West ———+——— East (+180)
|
South (-90)
So the point returned by Leaflet should be correct and mine should not make any sense - I don't understand why it's correctly drawn when flipped. Could be the reason why the polygon.getBounds()
LatLong's are also flipped.
Workaround: I found this working when switching the latLng coordinates of the bounds calculated by Leaflet. Sadly this turn the topics question to "Why are my coordinates flipped?" and leaves me with the workaround of just flipping them;
let coordinates = parsedJson.geometry.coordinates;
let polygon = L.polygon(coordinates);
let bounds = polygon.getBounds();
let southWest = bounds.getSouthWest();
let northEast = bounds.getNorthEast();
let cSouthWest = L.latLng(southWest.lng, southWest.lat);
let cNortEast = L.latLng(northEast.lng, northEast.lat);
let newBounds = L.latLngBounds(cSouthWest, cNortEast);
myMap.fitBounds(newBounds);