Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

javascript - 如何在传单地图中仅添加一个标记(How to add only one marker in leaflet map)

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);
    });
  ask by 1110 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...