How to switch between multiple map legends using leaflet.js?

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.

0
source share
1 answer

VODlegend || BUDlegend || Lislegend

In javascript this is a condition (the result is true or false) ... not the list you expect

You need to track your current control as

 SGlegend.addTo(map); currentLegend = SGlegend; map.on('baselayerchange', function (eventLayer) { if (eventLayer.name === 'Agricultural') { map.removeControl(currentLegend ); currentLegend = SGlegend; SGlegend.addTo(map); } else if (eventLayer.name === 'Building') { map.removeControl(currentLegend ); currentLegend = BUDlegend; BUDlegend.addTo(map); } else if (eventLayer.name === 'Forest') { map.removeControl(currentLegend ); currentLegend = LISlegend; LISlegend.addTo(map); } else if (eventLayer.name === 'Water') { map.removeControl(currentLegend ); currentLegend = VODlegend; VODlegend.addTo(map); } }) 

The modified fiddle is here: http://jsfiddle.net/FranceImage/X678g/

+1
source

Source: https://habr.com/ru/post/1245726/


All Articles