How to add only one marker in leaflet map

半世苍凉 提交于 2019-12-19 05:24:10

问题


I am adding marker on map on user click.
Problem is that I want only one marker but now whenever I click on map new marker is added.
I am trying 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);
    });

回答1:


Instead of using .on to capture and handle the event, you could use .once. That way the event will be only captured once and the handler will unbind itself after that.

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

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

If you're ever need to unbind a handler yourself you can use .off. Check the reference for event methods: http://leafletjs.com/reference.html#events

As to why your code above isn't working, on first click you're trying remove the marker: map.removeLayer(marker), but the variable marker doesn't contain a L.Marker instance so the map is unable to remove it. You should check if it's 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's a working example on Plunker: http://plnkr.co/edit/iEcivecU7HGajQqDWzVH?p=preview




回答2:


Use .off() to unbind 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 didn't test it but it should at least put you in the right direction.



来源:https://stackoverflow.com/questions/27609294/how-to-add-only-one-marker-in-leaflet-map

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