22

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/):

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

Separate function (http://jsfiddle.net/rhewitt/U6Gaa/6/):

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

3 回答 3

21

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

});

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);
}
});
于 2013-08-22T19:00:47.150 回答
12

主要问题是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);
}
于 2015-02-26T11:02:26.800 回答
-1
var marker = L.marker([35.737448286487595, 51.39876293182373]).addTo(map);
var popup = marker.bindPopup('<b>Hello world!</b><br />I am a popup.');
于 2019-09-23T11:46:15.943 回答