0

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.

2

... But they doesn't show up on the map at all.

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 to click events on it).

Your GeoJSON features have been converted into a L.Layer (either L.Markers, L.Polylines or L.Polygons) by the magic of L.GeoJSON - and those layers have received a style and have been added to the map - by the L.GeoJSON instance.

The issue here is a misunderstanding of what setStyle does here at

new L.FeatureGroup().setStyle(selectionStyle)

The setStyle method calls setStyle on any layers that are part of the group, but only at the time when setStyle is called. By the tone of your question, I assume that you expect selectionStyle 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 of L.LayerGroup/L.FeatureGroups. It's perfectly possible to do something like

var line = L.polyline(...);
var group1 = L.featureGroup().addTo(map).addLayer(line);
var group2 = L.featureGroup().addTo(map).addLayer(line);

(Which is what's happening in your case, but with one instance of L.GeoJSON and one of L.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 a L.FeatureGroup will not trigger any re-styling.

  • I got it to run. function featureClick(event) { var polygon = event.target; polygon.addTo(selectionLayer); selectionLayer.setStyle(selectionStyle(polygon.feature)); } – nlaan Sep 6 '18 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.