0

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

  • 4
    that method is implemented for singular leaflet feature objects ([circle]marker, popup, polyline) only, not for a layer object (if I interpret myLayer correctly) – ThingumaBob Sep 27 '18 at 7:03
5

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().

3

To elaborate on @Stefan_Fairphones answer and also add some minimal code example:

To fly to the feature on an event, use

document.getElementById("fly").addEventListener("click", function() {
  map.flyTo(myLayer.getBounds().getCenter(), 16);
});

I would always prefer the get-Methods over accessing "private" properties directly, but thats mainly style.

See corrected codepen at https://codepen.io/anon/pen/QZLMNg .

This needs some HTML element with the id fly, which i have added in the codepen.

Also, o a side note: If you don't need multiple features you could scrap the geojson completely and use markers directly:

  L.marker([41.77,-88.15]).addTo(map);

Markers can also use custom icons, see https://leafletjs.com/reference-1.3.4.html#divicon . Note the different order of the coordinates in the marker constructor from the geojson!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.