Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

javascript - How do you add marker to map using leaflet map.on('click', function) event handler

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

use

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...