I am trying to find a way to change the clustering radius depending on current zoom.
I want less clustering on higher zoom levels than on lower zoom levels, this is what I am trying to achieve, but it is not working very well, something is missing or done wrong...
map.on('zoomend', function() {
var currentZoom = map.getZoom();
if (currentZoom > 9) {
return 20
} else {
return 80
}
});
var mcg = new L.MarkerClusterGroup({
chunkedLoading: true,
maxClusterRadius: currentZoom,
})
Your
currentZoom
variable is declared within the inner scope of the event listener of your map zoomend event. You cannot access it outside that scope.Changing the primitive value assigned to a variable will not make all other assignments update accordingly. However, the Leaflet.markercluster plugin API does offer a way to cover this use case: instead of providing a primitive value to the
maxClusterRadius
option, provide a function that returns the radius for a given map zoom level:https://github.com/Leaflet/Leaflet.markercluster#other-options
Therefore in your case: