Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet.markercluster - how to count all markers in a markerClusterGroup?

I am using Leaflet.markercluster.

This is my code, basd upon the various related questions:

    // Takes an L.markerClusterGroup as input parameter
    Self.GetNumMarkersInClusterGroup = function(clusterGroup)
    {
        Self.map.eachLayer(function (layer) {
            if (layer.getChildCount) {
// somehow need to check here for our desired cluter group

                console.log('Cluster group has ' + layer._childClusters.length + 'layers')        ;
                console.log('With a total of ' + layer._childCount + ' markers');  
                }
        });
    }       // GetNumMarkersInClusterGroup()

but, layer.getChildCount is undefined :-( What am I doing wrongly?


Related questions:

  • iterate over cluster in markerCluster : leaflet
  • Count elements in MarkerCluster
  • Getting number of clusters and its markers with Leaflet?
  • Getting the childcount in leaflet markercluster
like image 596
Mawg says reinstate Monica Avatar asked Sep 01 '25 02:09

Mawg says reinstate Monica


1 Answers

It is true that there may be some confusion in how to use Leaflet.markercluster plugin:

  • There is the overall MarkerClusterGroup (MCG) object, i.e. what you get when calling L.markerClusterGroup()
  • the Cluster Markers, which are what the MCG displays on the map when your individual Markers are clustered together
  • the individual Markers that you add into an MCG

If your clusterGroup is actually an MCG, then you can simply use the fact that it extends Leaflet standard Feature Group and Layer Group, and in particular it has a getLayers() method:

Returns an array of all the layers added to the group.

So if you want the total number of Markers in your MCG, you can do e.g. clusterGroup.getLayers().length

For completeness, the MCG also has the methods referred to in the Leaflet.markercluster documentation as "group methods"

And the getChildCount() method (and getAllChildMarkers()) is for the Cluster Markers, which are e.g. what you get when using "clusterclick" event and the like.

like image 85
ghybs Avatar answered Sep 04 '25 03:09

ghybs