Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a marker using map.eachLayer of leaflet?

Tags:

marker

leaflet

I am able to display contents of clustered markes but could not display the contents of a single marker.

Please find the below code, where else statement will handle the single marker.

map.eachLayer(function(marker) {  
   if (marker.getChildCount) { // to get cluster marker details
     console.log('cluster length ' + marker.getAllChildMarkers().length);
   } else {
     // how to display the contents of a single marker ??

     alert(marker.options.title); // doesn't work
   }

Thanks.

like image 392
Kiran Patil Avatar asked Jan 26 '26 15:01

Kiran Patil


1 Answers

Remember that map.eachLayer() works on every layer of the map. This includes popups and the map tile layer, as well as markers and clusters of markers. Not all these types of layers will have the same options as markers or clusters. You will need to test to check whether each layer is a Marker, a cluster, or something else. Also, remember that markers may not necessarily have a title set.

This works for me:

map.eachLayer(function(layer) {
    if(layer.options && layer.options.pane === "markerPane") {
        alert("Marker [" + layer.options.title + "]");
    }
});
like image 199
JRI Avatar answered Jan 29 '26 14:01

JRI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!