stefanocudini / leaflet-panel-layers

Leaflet Control Layers extended with support groups and icons
https://opengeo.tech/maps/leaflet-panel-layers/
MIT License
286 stars 92 forks source link

`removeLayer()` not working properly from within `map.on` #68

Open designgears opened 1 year ago

designgears commented 1 year ago

When calling removeLayer() from within map.on event the baselayer menu gets a bit wonky. After removing even a single layer I can click thru the baselayers top to bottom just fine, but going out of order clicking at random requires I click the radio button twice. This also seemed to happen with overlay layers, requiring two clicks to check the box.

map.on('baselayerchange', (e) => {
    control.removeLayer(somelayergrouphere);
}

Removing a layer outside of the map.on event works as expected, the menu doesn't get wonky.

designgears commented 1 year ago

After some more digging I found that the order things are added and removed matter when inside map.on. (for reasons unknown to me)

https://github.com/stefanocudini/leaflet-panel-layers/blob/99f0ee2959454afbcbc5ec15b9804ea506519c31/src/leaflet-panel-layers.js#LL422C2-L431C2

You're looping over elements in the panel, while going down the list, the thing that comes first gets removed and the thing you clicked gets added. Going up the list, you add before you remove.

I fixed this by adding two vars, toBeAdded and toBeRemoved, replaced addLayer and removeLayer in the if/else and stored the object in those, then simply fired removeLayer(toBeRemoved) followed by addLayer(toBeAdded) after the if/else to guarantee we always do the remove before the add.