[GIS] Get Lat Lon out of function in Leaflet

leaflet

I'm wondering how can I get lat and lon out of the function in a variable with global scale in Leaflet. The code to get the coordinates per click in the map works fine but then I can't write my lat and lon in global variables. My code which doesn't work look like this:

var lat;
var lon;

function clickEvent(e) {

        if (typeof(newMarker)==='undefined'){
            newMarker = new L.marker(e.latlng, { draggable: true });
            newMarker.addTo(satMap);}
        else { newMarker.setLatLng(e.latlng);}


        lat = e.latlng.lat;
        lon = e.latlng.lng;
}

satMap.on('click', clickEvent);
document.write(lat);

Best Answer

I think you need to attach your function to a click event with .on('click').

For example:

var lat;
var lng;

map.on('click', function(e) {
    console.log(e.latlng);  //So you can see if it's working
    lat = e.latlng.lat;
    lng = e.latlng.lng;
});

There are different ways you can implement the function to include other things (like placing markers), but the main point in your case is the layer.on('click') part, otherwise it's not listening for a click. There are some good examples in this tutorial.

Related Question