Reputation: 93
I'm playing with Leaflet and I've created a map where I have some circle markers placed in one featureGroup and polygons in other featureGroups.
The circle markers are clickable points where once clicked, removes the layer from the map and adds the right featureGroup of polygons to the map. Right now I'm removing the featureGroup with circles by its name.
Is it possible to fetch the parent featureGroups' Name or ID when you click on one of the circle markers?
As I'm adding more featureGroups with clickable circles I'd like to dynamically remove the featureGroup from the map by the clicked circles parent featureGroup rather than referencing it directly.
Upvotes: 0
Views: 2970
Reputation: 19069
No.
Leaflet does not have a concept of "parent group". A L.Layer
can belong to zero, one, or many L.LayerGroup
s, e.g.:
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);
See that as a working example over here.
You might want to use the hasLayer
method to check if a given layer is in a group, though.
If you are not afraid of the Leaflet source code (and you've read the plugin tutorials and know a bit about the internal architecture), you can also monkey-patch this functionality, with something like:
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;
}
});
Upvotes: 4