Instead of using .on
to capture and handle the event, you could use .once
.(您可以使用.once
而不是使用.on
捕获和处理事件。)
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
.(如果您需要自己解除绑定处理程序,则可以使用.off
。)
Check the reference for event methods: http://leafletjs.com/reference.html#events(检查参考以了解事件方法: 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.(至于上述代码为何无法正常工作的原因,请先单击以尝试删除标记: map.removeLayer(marker)
,但是变量marker
不包含L.Marker实例,因此地图无法将其删除。)
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(这是有关Plunker的工作示例: http ://plnkr.co/edit/iEcivecU7HGajQqDWzVH?p=preview)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…