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

I`m using leaflet.js library to create multiple maps based on statistical data. Each map displays different range of values so it would be nice to change legend when user change map.

I found similar example in this question, but I need to switch between more than two layers. I try simply add more "if" statments and logical operators in code, but it doesn`t work right:

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 example of my map on jsfiddle. I would be grateful for any help.

Answers:

Answer

VODlegend || BUDlegend || LISlegend

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

You need to keep track of your current control like that

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);
    }
  })

Modified fiddle is here: http://jsfiddle.net/FranceImage/X678g/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.