4

In Leaflet, if I have a feature layer filled with markers, how do I get these markers back from the layer? I want to apply different popups to each individual marker, instead of the entire set. I can't find a method for this in the documentation.

2 Answers 2

4

The docs are great, look at the LayerGroup part. There is a method eachLayer that does exactly what you want:

featureLayer.eachLayer(function (layer) {
  // do something with marker layer

  // layer.feature is probably defined, to create marker, do something like this
  layer.bindPopup(createPopupContentFromFeature(layer.feature));
});

You can do similar things if you create L.GeoJSON layer with onEachFeature property. See the great tutorials on LeafletJS web.

2
  • No, that seems to bind the same popup to every feature in the layer. I want all the features in a layer individually. The code example there, map.eachLayer(function (layer) { layer.bindPopup('Hello'); }); Binds the same popup to all markers. I need different popups for every marker in a layer.
    – yesman
    Oct 10, 2014 at 6:41
  • You can do anything in the eachLayer(function(layer){...}) with each layer separately. As I suggest, your own function createPopupContentFromFeature(layer.feature) can create any popUp content you want based on feature data, that are unique for each marker.
    – mattes88
    Oct 10, 2014 at 13:17
0

You can try getting them all and then filtering, or using find() / findIndex().

let found = featureLayer.getLayers().filter(…)[0] ?? null;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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