Leaflet Error – Fixing L.geoJSON.getLatLng() is not a Function

leaflet

I am trying to get latlang of a marker so I can use it and fly to later.

map.flyTo(myLayer.getLatLng() ,16);

But why do I get getLatLng() not a function?

codepen example

Best Answer

getLatLng() is not a method of L.geoJSON. As far as I can see you have three options (in the order of what I would do):

1. Directly access the coordinates of the geojsonFeature:

var coord = geojsonFeature.geometry.coordinates;
map.flyTo([coord[1],coord[0]]); // inverted

2. Use the getBounds() method:

map.flyTo(myLayer.getBounds().getCenter());

3. Fly to the circle marker at (actually before) creation:

let myLayer = L.geoJSON(geojsonFeature, {
      pointToLayer: function (feature, latlng) {
        map.flyTo(latlng);
        return L.circleMarker(latlng, geojsonMarkerOptions);
    }
}).addTo(map);

PS.: Your codepen example has a typo: getLatLang() should be getLatLng().

Edit: Include @til_b's hint on LatLngBounds getCenter().