I have a geojsonLayer and a selectionLayer. I want to add specific features to the selectionLayer after a click event.
I create the selectionLayer at startup:
selectionLayer = new .FeatureGroup().setStyle(selectionStyle).addTo(map);
To the geojson layer I bind:
layer.on({
click: featureClick
})
Which contains:
function featureClick(event) {
event.target.addTo(selectionLayer)
}
This workes though, when I check selectionLayer.getLayers().length
, the feature is added. But they doesn't show up on the map at all.
Best Answer
They do... because they're already on the map, as part of your
L.GeoJSON
group.(I'm assuming that you have a
L.GeoJSON
added to the map, as you're reacting toclick
events on it).Your GeoJSON features have been converted into a
L.Layer
(eitherL.Marker
s,L.Polyline
s orL.Polygons
) by the magic ofL.GeoJSON
- and those layers have received a style and have been added to the map - by theL.GeoJSON
instance.The issue here is a misunderstanding of what
setStyle
does here atThe
setStyle
method callssetStyle
on any layers that are part of the group, but only at the time whensetStyle
is called. By the tone of your question, I assume that you expectselectionStyle
to be applied to layers when they're added to that group, which does not happen by design.Keep in mind that in Leaflet a
L.Layer
can be part of any number ofL.LayerGroup
/L.FeatureGroup
s. It's perfectly possible to do something like(Which is what's happening in your case, but with one instance of
L.GeoJSON
and one ofL.FeatureGroup
).If you want to change the styling of any
L.Layer
(on hover/click/selection/etc), do so explicitly. The Leaflet tutorial on interactive chloropeths has details on a way to do that. Adding layers to aL.FeatureGroup
will not trigger any re-styling.