Yashwant
Yashwant

Reputation: 213

Facing trouble with global variable in JS

Following code is to track user location,

var curr_loc; //global varible
function displayLocation(loc) {
    currLat = loc.coords.latitude;
    currLon = loc.coords.longitude;
    curr_loc = currLat + "," + currLon;
    alert(curr_loc); //Displaying latitude and longitude values 
}

function foo() {
    navigator.geolocation.getCurrentPosition(displayLocation);
    alert(curr_loc); //undefined
}
foo();

How can I access location values in foo method.

Upvotes: 1

Views: 62

Answers (1)

lanzz
lanzz

Reputation: 43198

navigator.geolocation.getCurrentPosition(displayLocation) returns before the position is established, and displayLocation would be called at some point in the future when the position is available. curr_loc is undefined for some time after navigator.geolocation.getCurrentPosition() returns, because displayLocation has not been called yet.

Upvotes: 1

Related Questions