我正在与Leaflet一起玩,并且创建了地图,在其中我将一些圆形标记放置在一个featureGroup中,并将多边形放置在其他FeatureGroup中。
圆形标记是可单击的点,一旦单击它们,就会从地图上移除图层,并向地图添加正确的多边形要素组。现在,我要删除带有圆圈名称的featureGroup。
单击圆形标记之一时,是否可以获取父要素组的名称或ID?
当我添加更多具有可单击圆的FeatureGroup时,我想通过单击的圆父FeatureGroup从地图上动态删除FeatureGroup,而不是直接引用它。
最佳答案
没有。
传单没有“父母组”的概念。 L.Layer
可以属于零,一个或多个L.LayerGroup
,例如:
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检查给定的图层是否在组中。如果您不怕Leaflet源代码(并且您已经阅读了插件教程并且对内部体系结构有所了解),则还可以通过以下方式猴子修补此功能:
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;
}
});