Leaflet add/remove legends with layer selection

僤鯓⒐⒋嵵緔 提交于 2019-12-08 02:32:20

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/22866486/leaflet-add-remove-legends-with-layer-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!