Matus Mucka
Matus Mucka

Reputation: 100

Global Javascript variables defined in the function

I am trying to make variables lat and loc global, but they are always zero.

var lat=0;
var loc=0;

navigator.geolocation.getCurrentPosition(function(position) {
     lat = position.coords.latitude;
     loc = position.coords.longitude;
});

alert(lat); // this eqals zero 

Upvotes: 0

Views: 69

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

That's an asynchronous call! Use this way:

navigator.geolocation.getCurrentPosition(function(position) {
    lat = position.coords.latitude;
    loc = position.coords.longitude;
    alert (lat);
});

Background

When you are firing alert(lat), the getCurrentPosition() wouldn't have fired and your value might have not set. If you wanna do something, put it or call it inside that function.

navigator.geolocation.getCurrentPosition(function(position) {
    lat = position.coords.latitude;
    loc = position.coords.longitude;
    // Something like this.
    calculate (lat, loc);
});

Upvotes: 2

Related Questions