user3498523
user3498523

Reputation: 370

Leaflet add/remove legends with layer selection

I'm new to Leaflet/JavaScript and have been struggling to get legends a map to show only when a specific layers 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:

http://jsfiddle.net/gerlis/T8DHb/3/

Any guidance would be greatly appreciated.

Upvotes: 2

Views: 7413

Answers (1)

Esko Piirainen
Esko Piirainen

Reputation: 1379

Your code needed just a couple of changes. Working fiddle: http://jsfiddle.net/T8DHb/8/

When you change the base layer, the even fired is not 'overlayadd', it is 'baselayerchange':

map.on('baselayerchange', function (eventLayer) {

You should only add to map the layer which you want to show for the default base layer. I added PermaFrost.

Also, you should only add to the map the legend which you want to go with the default base layer.

Upvotes: 2

Related Questions