Leaflet – Get a List of Leaflet Marker Clusters Within Current Map Bounds

leafletweb-mapping

I am using leaflet.markercluster plugin to show clusters on my map and getting information about each cluster on hover/click event.

What I'd like to do now is to write a method that if a user zooms or pans the map, it returns list of clusters within the current map bounds.

var option = {
    useCanvas: true,
    anchorWidth: 20,
    anchorHeight: 40,
    canvasPadding: 0.0,
    map: map
};
var clusterMarkers = L.markerClusterGroup(options, { chunkedLoading: true });

for(var i = 0;i<pakData.length;i++){
  option.lat = pakData[i][0];
  option.lng = pakData[i][1];    
var marker = TPLMaps.overlays.point(option);
clusterMarkers.addLayer(marker);

}
map.addLayer(clusterMarkers);
clusterMarkers.addEventListener('clusterclick', (e)=>{
    console.log(e); // I want list of these e.target within current bounds
})

Best Answer

It seems there is no exposed or internal method or array for enumerating current marker clusters. The only useful method seems to be .getVisibleParent, which returns visible parent cluster marker of given marker.

Method to obtain visible marker clusters is then simply brute force: iterate through all the markers, construct array of all visible marker clusters and check which one of those is really visible.

I this method is used within moveend event processing function, it has to be called with delay of about one second to let marker cluster processing be finished.

Code to log visible marker clusters on the console at each map move event could then look something like this (tested):

function logVisibleClusters() {
  var parent;
  var visibleClusterMarkers = [];
  var bounds = map.getBounds();
  clusterMarkers.eachLayer(function (marker) {
    parent = clusterMarkers.getVisibleParent(marker);
    if (parent && (typeof visibleClusterMarkers[parent._leaflet_id] == 'undefined')) {
      visibleClusterMarkers[parent._leaflet_id] = parent;
    }
  });
  visibleClusterMarkers.forEach(function(clusterMarker) {
    if (bounds.contains(clusterMarker._latlng)) {
      console.log('visible: ', clusterMarker);
    }
  });
}

map.on('moveend', function(e) {
  setTimeout(logVisibleClusters, 1000);
});
Related Question