Leaflet: how can I display a marker or legend only on one layer?

一世执手 提交于 2020-03-23 08:05:54

问题


I made a leaflet map with different layers which look like this:

L.easyButton('<span class ="buttons">Example </span>', function (btn, map) {
    if (map.hasLayer(example1)) {
        map.removeLayer(example1);
    };
    if (map.hasLayer(example2)) {
        map.removeLayer(example2);
    };
    if (map.hasLayer(example3)) {
        map.removeLayer(drittpa2017zweit);
    }
    map.addLayer(example4);
}, 'FirstExample').addTo(map);

and so on...
I declared a legend, which I only want to use when one layer is on, right now it appears all the time I think because of this

legendwahlbeteiligung.addTo(map);

I tried everything I saw on here to make it visible only on one layer but then they all disappear...
I have the same problem with a marker I use, which I also only want to show on one of the mentioned layer...
Can anyone tell me how I can make the legend and marker only appear when one layer is clicked on?


回答1:


To make a marker myMarker appear when the layer example1 is visible and disappear when it's not:

var myMarker = L.marker(...);

example1.on('add', function(e) {
   if (! map.hasLayer(myMarker)) {
       myMarker.addTo(map);
   }
});

example1.on('remove', function(e) {
   if (map.hasLayer(myMarker)) {
       myMarker.removeFrom(map);
   }
});


来源:https://stackoverflow.com/questions/60563661/leaflet-how-can-i-display-a-marker-or-legend-only-on-one-layer

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