這與以前的問題有關:Leafletjs dynamically bound map to visible overlays。Leafletjs動態綁定到可見標記/集羣
我現在使用Leaflet.FeatureGroup.SubGroup
插件與Leaflet.markercluster
插件。嘗試設置綁定到所有可見標記和標記簇的映射。我使用3座標來測試:
[43.6425657, -79.38705569999999]
[43.7164673, -79.3395846]
[-41.3142772, 174.8135975]
這是迄今爲止代碼:
var map = L.map("mapid");
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png").addTo(map);
map.setView([43.6532, -79.3832], 2);
var parentGroup = L.markerClusterGroup().addTo(map),
consultingMarkers = L.featureGroup.subGroup(parentGroup).addTo(map),
otherMarkers = L.featureGroup.subGroup(parentGroup).addTo(map);
// subGroup1
L.marker([43.6425657, -79.38705569999999]).addTo(consultingMarkers);
L.marker([43.7164673, -79.3395846]).addTo(consultingMarkers);
// subGroup2
L.marker([-41.3142772, 174.8135975], {icon: otherIcon}).addTo(otherMarkers);
var overlays = {
'consulting': consultingMarkers,
'other': otherMarkers
};
L.control.layers(null, overlays, {
collapsed: false
}).addTo(map);
map.on('overlayadd overlayremove', function() {
var bounds = parentGroup.getBounds(),
southWest = bounds.getSouthWest();
// Fit bounds only if the Parent Group actually has some markers,
// i.e. it returns valid bounds.
if (southWest && !southWest.equals(bounds.getNorthEast())) {
map.fitBounds(parentGroup.getBounds());
}
});
到目前爲止,我遇到了這些問題:
- 地圖不綁定到[-41.3142772,174.8135975]座標
- 取消檢查「諮詢」圖層不會將地圖綁定到具有座標的「其他」圖層的標記[-41.314277 2,174.8135975]。
更新:它似乎有單個標記的邊界問題。我嘗試添加另一個標記座標[43.76089289999999,-79.4103427],它將在集羣中。但如果我刪除「諮詢」羣集並刪除「其他」層。地圖仍然沒有綁定到地圖上剩下的最後一個標記。
感謝您澄清'SouthWest'和'NorthEast'檢查。通過用'bounds.isValid()'取代檢查,現在它在更新地圖時起作用。我還爲映射加載時添加了一個'map.fitBounds(parentGroup.getBounds());',因此它將綁定到可見標記。 – teresa