[GIS] Getting number of clusters and its markers with Leaflet

clusteringleafletmarkers

I would like to know the number of clusters and its markers as soon as I open the map without zoom-in.

I'm using:

  • Leaflet 1.2.0
  • Leaflet.MarkerCluster 1.2.0
  • Firefox 57.0.1
  • OS/Platform

On the image below the expected result is demonstrated. It should represent:

  • 1 cluster with 6 markers (marker1, marker2, marker4, marker5, marker6, marker7)
  • for each marker its details (name, lat, lon, …)

enter image description here

Best Answer

For total number of markers/layers you can use the getLayers() function which will return an array of all the component layers of that cluster.

var testCluster = L.markerClusterGroup();
L.marker([event.latlng.lat, event.latlng.lng]).addTo(testCluster);
testCluster.getLayers();

It will return array of each marker as layer.

Alternatively You can use this:

map.eachLayer(function (layer) {
        if (layer.getChildCount){     
            console.log(layer._childClusters.length)        
            console.log(layer._childCount);  
            }
    });