How to remove a marker from a booklet map

I add a marker to the map when the user clicks.
The problem is that I want only one marker, but now when I click on the map, a new marker is added.
I try to remove it, but nothing happens:

var marker; map.on('click', function (e) { map.removeLayer(marker) marker = new L.Marker(e.latlng, { draggable: true }); marker.bindPopup("<strong>" + e.latlng + "</strong>").addTo(map); marker.on('dragend', markerDrag); }); 
+5
source share
2 answers

Instead of using .on to capture and handle the event, you can use .once . Thus, the event will be recorded only once, and after that the handler will untie itself.

 map.on('click', function () { console.log('I fire every click'); }); map.once('click', function () { console.log('I fire only once'); }); 

If you ever need to untie the handler yourself, you can use .off . Check out the link to event methods: http://leafletjs.com/reference.html#events

As for why your code above does not work, the first time you try to remove the marker: map.removeLayer(marker) , but the marker variable does not contain an instance of L.Marker, so the map cannot remove this. You need to check if this is defined first, and only then remove it:

 var marker; map.on('click', function (e) { if (marker) { // check map.removeLayer(marker); // remove } marker = new L.Marker(e.latlng); // set }); 

Here is a working example on Plunker: http://plnkr.co/edit/iEcivecU7HGajQqDWzVH?p=preview

+7
source

Use . off () to cancel the on click event.

It should be something like:

 var marker; map.on('click', mapClicked); function mapClicked(e) { map.off('click', mapClicked); map.removeLayer(marker) marker = new L.Marker(e.latlng, { draggable: true }); marker.bindPopup("<strong>" + e.latlng + "</strong>").addTo(map); marker.on('dragend', markerDrag); } 

I have not tested it, but it should at least put you in the right direction.

+2
source

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


All Articles