Javascript 如何在传单地图中仅添加一个标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27609294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add only one marker in leaflet map
提问by 1110
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);
});
回答by iH8
Instead of using .onto 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.
而不是使用的.on捕获和处理的情况下,你可以使用.once。这样事件只会被捕获一次,处理程序将在此之后解除绑定。
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
如果您需要自己解除绑定处理程序,您可以使用.off. 检查事件方法的参考: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 markerdoesn'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:
至于为什么上面的代码不起作用,在第一次单击时,您尝试删除标记:map.removeLayer(marker),但变量marker不包含 L.Marker 实例,因此地图无法删除它。您应该先检查它是否已定义,然后才将其删除:
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
这是一个关于 Plunker 的工作示例:http://plnkr.co/edit/iEcivecU7HGajQqDWzVH?p=preview
回答by grim
Use .off()to unbind the on click event.
使用.off()解除点击事件的绑定。
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.
我没有测试它,但它至少应该让你朝着正确的方向前进。

