简体   繁体   中英

How to remove Leaflet Marker in L.easyButton?

I'm using an L.easyButton to add and remove a leaflet marker based on the current location. This is my code:

var marker;

L.easyButton({
    states: [{
        stateName: 'on',
        title: 'Add Marker',
        onClick: function(btn, map) {
            map.locate({ setView: true, maxZoom: 16 });

            function onLocationFound(e) {
                marker = L.marker(e.latlng).addTo(map);
            }
            map.on('locationfound', onLocationFound);
            btn.state('off');
        }
    }, {
        stateName: 'off',
        title: 'Remove Marker',
        onClick: function(btn, map) {
            if (map.hasLayer(marker)) {
               map.removeLayer(marker); 
               //map.removeControl(marker);        
           }
            btn.state('on');
        }
    }]
}).addTo(map);

The code works well when added and removed the marker for the first time. But when I clicked the button again, the marker can added, but it failed to be removed.

FYI, the button state can be changed successfully, just the removal function is not working.

I have tried these both code lines in the remove function, but it didn't work.

map.removeLayer(marker); 
map.removeControl(marker);

How should I improve the code? Thanks in advance.

What happens is that the next times you request a geolocation and create a corresponding Marker, you actually stack up your event listener, hence create several Markers at the same position.

Therefore when trying to remove it later on, the very last one is correctly removed, but there are still some Markers at that position, leading to the impression that nothing happened.

A simple solution consists in removing the event listener after it has been used, typically with .once() method (instead of .on() ):

map.once('locationfound', onLocationFound);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM