Search code examples
javascriptleafletzoomingleaflet.markercluster

Change ClusterRadius depending on current zoom Leaflet


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,
})

Solution

    1. 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.

    2. 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

    You can also use a function that accepts the current map zoom and returns the maximum cluster radius in pixels.

    Therefore in your case:

    L.markerClusterGroup({
        chunkedLoading: true,
        maxClusterRadius: function (mapZoom) {
            if (mapZoom > 9) {
                return 20;
            } else {
                return 80;
            }
        },
    });