2016-11-30 120 views
0

我正在玩Leaflet,並創建了一個地圖,其中一些circle標記放置在一個featureGroup中,另一個featureGroup中放置多邊形。如何在點擊圖層時獲取featureGroup的名稱/ ID

圓形標記是可點擊的點,其中一旦單擊該點,將從地圖中移除圖層,並將右側的多邊形featureGroup添加到地圖中。現在,我將通過名稱刪除帶有圓圈的featureGroup。

是否有可能當你點擊圓圈標記之一來獲取父featureGroups' 名稱ID

由於我添加更多featureGroups與可點擊的圈子,我想通過點擊的圈子parent featureGroup從地圖動態刪除featureGroup,而不是直接引用它。

回答

3

宣傳單沒有「父組」的概念。一個L.Layer可以屬於零個,一個或多個L.LayerGroup S,例如: -

var kyiv = [50.5, 30.5], 
    lnd = [51.51, -0.12], 
    sf = [37.77, -122.42], 
    dc = [38.91, -77.04], 
    trd = [63.41, 10.41], 
    mad = [40.40, -3.7]; 

var markerKyiv = L.marker(kyiv).addTo(all), 
    markerLnd = L.marker(lnd).addTo(all), 
    markerDC = L.marker(dc).addTo(all), 
    markerSF = L.marker(sf).addTo(all), 
    markerTrd = L.marker(trd).addTo(all), 
    markerMad = L.marker(mad).addTo(all); 

var euro = L.featureGroup([markerTrd, markerMad, markerKyiv, markerLnd]).addTo(map); 
var usa = L.featureGroup([markerDC, markerSF]).addTo(map); 
var northern = L.featureGroup([markerTrd, markerKyiv, markerLnd]).addTo(map); 
var southern = L.featureGroup([markerDC, markerSF, markerMad]).addTo(map); 

L.control.layers({},{ 
    Euro: euro, 
    USA: usa, 
    Northern: northern, 
    Southern: southern 
},{ 
    collapsed:false 
}).addTo(map); 

看到,作爲一個工作示例over here

儘管您可能想使用hasLayer method來檢查給定圖層是否在組中。

如果你不怕單張源代碼(並且您已經閱讀插件教程和了解了一下內部結構),你也可以猴子補丁此功能,喜歡的東西:

L.LayerGroup.include({ 
    addLayer: function (layer) { 
     var id = this.getLayerId(layer); 
     this._layers[id] = layer; 
     if (this._map) { 
      this._map.addLayer(layer); 
     } 

     // Add this group to the layer's known groups 
     layer._groups.push(this); 

     return this; 
    }, 

    removeLayer: function (layer) { 
     var id = layer in this._layers ? layer : this.getLayerId(layer); 
     if (this._map && this._layers[id]) { 
      this._map.removeLayer(this._layers[id]); 
     } 
     delete this._layers[id]; 

     // Remove this group from the layer's known groups 
     layer._groups.splice(layer._groups.indexOf(this), 1); 

     return this; 
    } 
}); 

// Make sure to init a property in L.Layer 
L.Layer.addInitHook(function(){ 
    this._groups = []; 
}); 

// Add a public getter for the layer's groups 
L.Layer.include({ 
    getGroups: function() { 
     return this._groups; 
    } 
}); 
+0

謝謝伊萬! – Dixos