2017-07-27 19 views
0

這與以前的問題有關:Leafletjs dynamically bound map to visible overlaysLeafletjs動態綁定到可見標記/集羣

我現在使用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()); 
    } 
}); 

到目前爲止,我遇到了這些問題:

  1. 地圖不綁定到[-41.3142772,174.8135975]座標
  2. 取消檢查「諮詢」圖層不會將地圖綁定到具有座標的「其他」圖層的標記[-41.314277 2,174.8135975]。

更新:它似乎有單個標記的邊界問題。我嘗試添加另一個標記座標[43.76089289999999,-79.4103427],它將在集羣中。但如果我刪除「諮詢」羣集並刪除「其他」層。地圖仍然沒有綁定到地圖上剩下的最後一個標記。

回答

1

如果我理解正確,你很困惑,因爲當你的一個SubGroups只有一個標記時,map.fitBounds看起來不會被執行?

在這種情況下,這只是!southWest.equals(bounds.getNorthEast())檢查的預期行爲:當bounds表示空區域時,它避免執行下一個塊,即存在0或1個標記。

通過替換bounds.isValid()的檢查,您可以避免只有0標記時的情況,但如果只有一個標記,它將允許執行下一個塊,因此嘗試將邊界放在空區域上。在這種情況下,小冊子會擺放到該標記並放大到maxZoom

map.on('overlayadd overlayremove', function() { 
    var bounds = parentGroup.getBounds(); 

    if (bounds.isValid()) { 
    map.fitBounds(bounds); 
    } 
}); 

演示:https://jsfiddle.net/3v7hd2vx/355/

+0

感謝您澄清'SouthWest'和'NorthEast'檢查。通過用'bounds.isValid()'取代檢查,現在它在更新地圖時起作用。我還爲映射加載時添加了一個'map.fitBounds(parentGroup.getBounds());',因此它將綁定到可見標記。 – teresa