问题
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