我有一个带有缩放级别2-7并使用MarkerCluster插件的传单地图,默认情况下,我让L.MarkerClusterGroup禁用了缩放级别2(这意味着没有集群),并且我试图允许用户单击一个按钮,然后将集群缩放级别更改为5。这可能吗?
我知道我可以通过创建两个标记集群组来做到这一点,一个没有集群,另一个有基于单击的集群和删除/添加,但这看起来非常混乱。真的,有几种方法可以做到,但它们实在太笨重了。
代码:
默认值(2是缩放的最低级别):
var markers = new L.MarkerClusterGroup (
{
disableClusteringAtZoom: 2,
maxClusterRadius: 100,
animateAddingMarkers: true
});我想要做的是:
$('#mcluster').click(function() {
//do some code that sets the disableClusterAtZoom to 5
});发布于 2015-09-09 16:35:19
我无法在缩放时找到禁用集群或为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);
}
});我相信有一个更优雅的解决方案,但随着我的知识仍在增长,这就是我想出的。
发布于 2016-01-07 09:04:38
我知道几个月前你需要一个解决方案,但是为了让你知道我最近为Leaflet.markercluster发布了一个子插件,它可以执行你想要的功能(只需要一些额外的代码):Leaflet.MarkerCluster.Freezable (演示这里)。
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);https://stackoverflow.com/questions/32480469
复制相似问题