0

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 
Matus Mucka
  • 100
  • 7

1 Answers1

2

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);
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252