如何使用leaflet map.on('click',function)事件处理程序添加标记到地图 [英] How do you add marker to map using leaflet map.on('click', function) event handler

查看:6092
本文介绍了如何使用leaflet map.on('click',function)事件处理程序添加标记到地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
}


推荐答案

在你的小提琴码中,你的功能范围错误。尝试移动地图函数内的函数,而不是在自己的范围内,即代替:

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);
}
});

这篇关于如何使用leaflet map.on('click',function)事件处理程序添加标记到地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆