根据当前缩放 Leaflet 更改 ClusterRadius

Change ClusterRadius depending on current zoom Leaflet

我正在尝试找到一种方法来根据当前缩放更改聚类半径。

我希望在较高缩放级别上的聚类比在较低缩放级别上的聚类少,这是我正在努力实现的目标,但效果不是很好,缺少某些东西或做错了...

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,
})
  1. 您的 currentZoom 变量是在地图 zoomend 事件的事件侦听器的内部范围内声明的。您无法在该范围之外访问它。

  2. 更改分配给变量的原始值不会使所有其他分配相应地更新。但是,Leaflet.markercluster 插件 API 确实提供了一种方法来涵盖此用例:不是为 maxClusterRadius 选项提供原始值,而是提供一个 returns 半径的函数对于给定的地图缩放级别:

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.

因此在你的情况下:

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