[英]How to change cluster zoom level on click with Leaflet map?
我有一個具有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
});
我找不到禁用群集的方法,也無法為zoomClustering設置新值,但是我發現了一種不太笨拙的方法。
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);
}
});
我敢肯定有一個更優雅的解決方案,但是隨着我不斷增長的知識,這就是我想到的。
我知道幾個月前您需要一個解決方案,但是為了讓您知道,我最近發布了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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.