javascriptleafletmapboxtilemill

Tilemill legend persists after unloading layer in Leaflet's L.control.layers


Please observe my map: http://bl.ocks.org/GotC/ab8315f6641e841442a9

I have two layers in a map. The Geomorfology layer has a Tilemill legend attached to it. The legend activates when loaded, as intended, but does not unload when the street layer is activated. I am inexperienced in using javascript and my hypothesis is that the .on('unload', function()) script is erroneous, but I cannot pinpoint the error.

Any help is appreciated.

Greetings, Rob


Solution

  • You can listen to the map's baselayerchange event instead:

    map.on('baselayerchange', function (event) {
        var legend = geomorfologie.getTileJSON().legend;
    
        console.log('baselayerchange to ' + event.name);
    
        if (event.name === 'Streets') {
            map.legendControl.removeLegend(legend);
        }
    
        if (event.name === 'Geomorfologie') {
            map.legendControl.addLegend(legend);
        }
    });
    

    DEMO