0

It sounds super simple, but I am looking to update my global variables ('latitude' and 'longitude') every time the map is clicked, as need to use these values elsewhere. Updating the variables from inside the function does not apply. Thus, the alerts show 'undefined'.

Any guidance would be much appreciated :-)

// set global vars
var latitude;
var longitude;
var popup = L.popup();

// create function to populate pop-up and global vars
function onMapClick(e) {  // show pop-up when map is clicked
  popup .setLatLng(e.latlng) .setContent("You clicked the map at " + e.latlng.toString()) .openOn(mymap); // populate pop-up with lat/long values
  latitude = e.latlng.lat // populate global var to use elsewhere
  longitude = e.latlng.lng // populate global var to use elsewhere
}

mymap.on('click', onMapClick);  // call function when cliked on map

alert(latitude) // output is 'undefined'
alert(longitude) // output is 'undefined'

1 Answer 1

1

The variables get updated. The only thing is that your alert calls have already happened. They aren't going to get done again when the click happens unless you write code to do them again when the click happens. Just move the alert calls (or whatever you're really doing with that information) into the click handler:

// set global vars
var latitude;
var longitude;
var popup = L.popup();

// create function to populate pop-up and global vars
function onMapClick(e) {  // show pop-up when map is clicked
    popup .setLatLng(e.latlng).setContent("You clicked the map at " + e.latlng.toString()).openOn(mymap); // populate pop-up with lat/long values
    latitude = e.latlng.lat; // populate global var to use elsewhere
    longitude = e.latlng.lng; // populate global var to use elsewhere
    alert(latitude);  // <===== Moved
    alert(longitude); // <===== Moved
}

mymap.on('click', onMapClick);  // call function when cliked on map

This also means you may well not need the globals at all:

// set global vars
var popup = L.popup();

// create function to populate pop-up and global vars
function onMapClick(e) {  // show pop-up when map is clicked
    popup .setLatLng(e.latlng).setContent("You clicked the map at " + e.latlng.toString()).openOn(mymap); // populate pop-up with lat/long values
    alert(e.latlng.lat);
    alert(e.latlng.lng);
}

mymap.on('click', onMapClick);  // call function when cliked on map
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.