I'm new to Leaflet/Javascript and have been struggling to get legends a map to show only when a specific layer is selected from the layer control. I have three layers, one of which I would like to have no legend and two others that have a corresponding legend. I came across an example, but have not been able to make it work:
// Add and remove legend from layers
map.on('overlayadd', function (eventLayer) {
// Switch to the Permafrost legend...
if (eventLayer.name === 'Permafrost') {
this.removeControl(legend1);
legend2.addTo(this);}
else { // Or switch to the treeline legend...
this.removeControl(legend2);
legend1.addTo(this);
}});
I created a jsfiddle with the specific example: