问题描述
我要在用户点击时在地图上添加标记.
问题是我只需要一个标记,但是现在单击地图时会添加新的标记.
我正在尝试将其删除,但没有任何反应:
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);
});
推荐答案
可以使用.once
代替使用.on
捕获和处理事件.这样,事件将仅被捕获一次,并且处理程序将在此之后解除绑定.
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');
});
如果您需要自己解除绑定处理程序,则可以使用.off
.检查事件方法的引用: 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的一个工作示例: =预览
Here's a working example on Plunker: http://plnkr.co/edit/iEcivecU7HGajQqDWzVH?p=preview
这篇关于如何在传单地图中仅添加一个标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!