Monday, May 20, 2024
141
rated 0 times [  144] [ 3]  / answers: 1 / hits: 73832  / 11 Years ago, thu, august 22, 2013, 12:00:00

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

More From » event-handling

 Answers
17

In your fiddle code, the 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 (note the 2 brackets moved further down)


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

});

[#76205] Thursday, August 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trayvon

Total Points: 35
Total Questions: 117
Total Answers: 88

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;