如何使用传单 map.on('click', function) 事件处理程序将标记添加到地图

2022-01-12 00:00:00 leaflet event-handling javascript

我正在尝试使用事件处理程序向地图添加标记.我可以使用回调函数来管理它,但是当我将函数与事件处理程序分开时就不行了.

I'm trying to use an event handler to add a marker to the map. I can manage this with a callback function, but not when I separate the function from the event handler.

回调(http://fiddle.jshell.net/rhewitt/U6Gaa/7/):

map.on('click', function(e){
    var marker = new L.marker(e.latlng).addTo(map);
});

独立函数(http://jsfiddle.net/rhewitt/U6Gaa/6/):

function newMarker(e){
    var marker = new L.marker(e.latlng).addTo(map);
}

推荐答案

在你的小提琴代码中,你的函数在错误的范围内.尝试在 map 函数内移动函数,而不是在它自己的范围内......即,而不是:

in your fiddle code, your function is in the wrong scope. try moving the function inside the map function instead of in it's own scope... i.e. instead of:

});

function addMarker(e){
// Add marker to map at click location; add popup window
var newMarker = new L.marker(e.latlng).addTo(map);
}

使用

function addMarker(e){
// Add marker to map at click location; add popup window
var newMarker = new L.marker(e.latlng).addTo(map);
}
});

相关文章