javascript 如何使用传单 map.on('click', function) 事件处理程序向地图添加标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18388288/
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 do you add marker to map using leaflet map.on('click', function) event handler
提问by Roy
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.
我正在尝试使用事件处理程序向地图添加标记。我可以使用回调函数来管理它,但是当我将函数与事件处理程序分开时就不行了。
Callback (http://fiddle.jshell.net/rhewitt/U6Gaa/7/):
回调(http://fiddle.jshell.net/rhewitt/U6Gaa/7/):
map.on('click', function(e){
var marker = new L.marker(e.latlng).addTo(map);
});
Separate function (http://jsfiddle.net/rhewitt/U6Gaa/6/):
单独的功能(http://jsfiddle.net/rhewitt/U6Gaa/6/):
function newMarker(e){
var marker = new L.marker(e.latlng).addTo(map);
}
回答by Claies
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:
在您的小提琴代码中,您的函数在错误的范围内。尝试在 map 函数内移动函数而不是在它自己的范围内移动......即而不是:
});
function addMarker(e){
// Add marker to map at click location; add popup window
var newMarker = new L.marker(e.latlng).addTo(map);
}
use
利用
function addMarker(e){
// Add marker to map at click location; add popup window
var newMarker = new L.marker(e.latlng).addTo(map);
}
});
回答by Melo
The main problem is that the variable mapthat you use inside the function addMarkeris not the variable in which you store the created map. There are several ways to solve this problem but the easiest can be to assign the created map to the variable mapdeclared in the first line. Here is the code:
主要问题是map您在函数内部使用addMarker的变量不是您存储创建的映射的变量。有几种方法可以解决这个问题,但最简单的方法是将创建的映射分配给map第一行中声明的变量。这是代码:
var map, newMarker, markerLocation;
$(function(){
// Initialize the map
// This variable map is inside the scope of the jQuery function.
// var map = L.map('map').setView([38.487, -75.641], 8);
// Now map reference the global map declared in the first line
map = L.map('map').setView([38.487, -75.641], 8);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
maxZoom: 18
}).addTo(map);
newMarkerGroup = new L.LayerGroup();
map.on('click', addMarker);
});
function addMarker(e){
// Add marker to map at click location; add popup window
var newMarker = new L.marker(e.latlng).addTo(map);
}
回答by Hamed Soleymani
var marker = L.marker([35.737448286487595, 51.39876293182373]).addTo(map);
var popup = marker.bindPopup('<b>Hello world!</b><br />I am a popup.');

