如何使用Leaflet map更改群集缩放级别?

时间:2015-09-09 13:09:42

标签: javascript leaflet markerclusterer

我有一个小叶地图,其缩放级别为2-7,并使用MarkerCluster插件,默认情况下,我有L.MarkerClusterGroup禁用群集缩放级别2(这意味着没有群集),我试图允许用户单击一个按钮,然后将聚类缩放级别更改为5.这可能吗?

我知道我可以通过制作两个markercluster组来实现它,一个没有聚类,一个具有聚类,并根据点击删除/添加它,但这看起来非常混乱。真的,有几种方法可以做到,但它们非常笨重。

代码:

默认值(2是最低缩放级别):

var markers = new L.MarkerClusterGroup (
    {
        disableClusteringAtZoom: 2,
        maxClusterRadius: 100,
        animateAddingMarkers: true
    });

我想做的事情是:

 $('#mcluster').click(function() {
    //do some code that sets the disableClusterAtZoom to 5
});

2 个答案:

答案 0 :(得分:0)

我无法找到一种方法来禁用群集或在缩放时为disableClustering设置新值,但我发现了一种不那么笨重的方法来实现这一点。

var markers = new L.LayerGroup(); //non cluster layer is added to map
markers.addTo(map);
var clusters = new L.MarkerClusterGroup (
    {
        disableClusteringAtZoom: 5,
        maxClusterRadius: 100,
        animateAddingMarkers: true
    }); //cluster layer is set and waiting to be used

var clusterStatus = 'no'; //since non cluster group is on by default, the status for cluster is set to no
 $('#mcluster').click(function( event ) {
    if(clusterStatus === 'no'){
        clusterStatus = 'yes';
        var current1 = markers.getLayers(); //get current layers in markers
        map.removeLayer(markers); // remove markers from map
        clusters.clearLayers(); // clear any layers in clusters just in case
        current1.forEach(function(item) {  //loop through the current layers and add them to clusters
            clusters.addLayer(item);
        });
        map.addLayer(clusters);
    } else {
        clusterStatus = 'no';  //we're turning off clustering here
        var current2 = clusters.getLayers(); //same code as before just reversed
        map.removeLayer(clusters);
        markers.clearLayers();
        current2.forEach(function(item) {
            markers.addLayer(item);
        });
        map.addLayer(markers);
    }
});

我确信有更优雅的解决方案,但凭借我不断增长的知识,这就是我想出来的。

答案 1 :(得分:0)

我知道你几个月前需要一个解决方案,但只是为了让你知道我最近发布了一个Leaflet.markercluster的子插件,它可以完全满足你的需求(带一些额外的代码):< strong> Leaflet.MarkerCluster.Freezable (演示here)。

var mcg = L.markerClusterGroup().addTo(map),
    disableClusteringAtZoom = 2;

function changeClustering() {
    if (map.getZoom() >= disableClusteringAtZoom) {
        mcg.disableClustering(); // New method from sub-plugin.
    } else {
        mcg.enableClustering(); // New method from sub-plugin.
    }
}

map.on("zoomend", changeClustering);

$('#mcluster').click(function () {
    disableClusteringAtZoom = (disableClusteringAtZoom === 2) ? 5 : 2;
    changeClustering();
});

mcg.addLayers(arrayOfMarkers);

// Initially disabled, as if disableClusteringAtZoom option were at 2.
changeClustering();

演示:http://jsfiddle.net/fqnbwg3q/3/

注意:在上面的演示中,我使用了一个细化来确保在重新启用群集时标记与动画合并。只需在使用enableClustering()之前使用超时:

// Use a timeout to trigger clustering after the zoom has ended,
// and make sure markers animate.
setTimeout(function () {
    mcg.enableClustering();
}, 0);