I use the leaflet.js library to create multiple maps based on statistics. Each map displays a different range of values, so it would be nice to change the legend when the user changes the map.
I found a similar example in question , but I need to switch between more than two layers. I'm just trying to add “if” and logical operators to the code, but it doesn't work correctly:
map.on('baselayerchange', function (eventLayer) { if (eventLayer.name === 'Agricultural') { map.removeControl(VODlegend || BUDlegend || LISlegend); SGlegend.addTo(map); } else if (eventLayer.name === 'Building') { map.removeControl(SGlegend || LISlegend || VODlegend); BUDlegend.addTo(map); } else if (eventLayer.name === 'Forest') { map.removeControl(BUDlegend || VODlegend || SGlegend); LISlegend.addTo(map); } else if (eventLayer.name === 'Water') { map.removeControl(LISlegend || SGlegend || BUDlegend); VODlegend.addTo(map); } })
Here is an example of my card on jsfiddle. I would appreciate any help.
source share