3

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:

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551

1 Answers1

5

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.

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
ghybs
  • 47,565
  • 6
  • 74
  • 99
  • 1
    Thanks for the answer, and the explanation. I can see now that I should not be using `getAllChildMarkers()` when not handling an event. I just want to get than number of markers in an MCG, e.g just after having parsed data & add markers to multiple groups. – Mawg says reinstate Monica Jan 16 '21 at 10:44