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
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.
-
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.– yesmanOct 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.– mattes88Oct 10, 2014 at 13:17
You can try getting them all and then filtering, or using find()
/ findIndex()
.
let found = featureLayer.getLayers().filter(…)[0] ?? null;