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 
7
  • 2
    What does alert(lat) say inside the function? Commented Jul 3, 2015 at 14:29
  • possible duplicate of how to change value of global variable inside of function Commented Jul 3, 2015 at 14:31
  • @DavidRobinson Nopes. This is not that case! Commented Jul 3, 2015 at 14:31
  • @PraveenKumar See Spudley's comment on the first answer Commented Jul 3, 2015 at 14:31
  • 1
    Nice, that's what I explained in my answer! @DavidRobinson! Still not a duplicate of that answer. Commented Jul 3, 2015 at 14:32

1 Answer 1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.