Leaflet add / remove legends with layer selection

I'm new to Leaflet / JavaScript and struggling to get the legends on the map to show only when certain layers are selected from the level control. I have three layers, one of which I would like to have without a legend and two others that have a corresponding legend. I came across an example, but could not get it to 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 jsfiddle with a specific example:

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

Everyone is welcome any guide.

+2
source share
1 answer

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

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

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

You should add only to display the layer that you want to show for the base level by default. I added PermaFrost.

In addition, you should only add to the map the legend that you want to use with the default base level.

+2
source

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


All Articles