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

Roy*_*Roy 13 event-handling leaflet

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

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

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

独立功能(http://jsfiddle.net/rhewitt/U6Gaa/6/):

function newMarker(e){
    var marker = new L.marker(e.latlng).addTo(map);
}
Run Code Online (Sandbox Code Playgroud)

Cla*_*ies 18

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

});

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

使用

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


小智 10

主要问题是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 &copy; <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);
}
Run Code Online (Sandbox Code Playgroud)