I am trying to use javascript to get a user’s geolocation so i can then use that information as a parameter in another section of javascript code, however I can’t get the scope right.
This is my code. Doing the alert inside the success function works fine, but if i try to access var lat anywhere outside the function, i get undefined value. How would I go about fixing this?
var lat; var long;
function success(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
alert(lat);
}
function error(msg) {
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}
You want your code to work like this:
But,
success()has not been called yet, solatis still undefined. That’s what your success handler is for. All the code that needs to be executed after you’ve retrieved the location goes in the success handler. This would work: