如何从传单地图中删除标记
我在用户点击时在地图上添加标记。
问题是我只想要一个标记,但现在每当我点击地图时都会添加新标记。
I我试图删除它但没有任何反应:
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);
});
而不是使用 .on
要捕获和处理事件,您可以使用 .once
。这样,事件将只捕获一次,然后处理程序将解除绑定。
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');
});
如果您需要自行取消绑定处理程序,可以使用。关
。检查事件方法的参考: http://leafletjs.com/reference.html#events
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
至于为什么上面的代码无法正常工作,首次点击时你会尝试删除标记: map.removeLayer(marker)
,但变量 marker
不包含L.Marker实例,因此地图无法删除它。您应该先检查它是否已经定义,然后将其删除:
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
});
这是关于Plunker的一个工作示例: http://plnkr.co/edit/iEcivecU7HGajQqDWzVH?p=preview
Here's a working example on Plunker: http://plnkr.co/edit/iEcivecU7HGajQqDWzVH?p=preview