Search code examples
leafletmarker

How to find a marker using map.eachLayer of 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.


Solution

  • 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 + "]");
        }
    });