0

I want to update my global variables, which are intended to hold values for my coordinates. They have their values only inside the function, not outside (globally). To be honest it's driving me crazy. If I want to use their values I have to call function within a function... which makes no sense to me (I prefer calling the function separately). Below is my code:

var lat = '';
var lon = '';
navigator.geolocation.getCurrentPosition(succes, error);

function succes(position){
    var crd = position.coords;
    lat = crd.latitude;
    console.log('inside: '+lat);

}

function error(err){
    console.warn(err.code + ': ' + err.message);
}

console.log('outside: '+lat);

Any idea why it happens?

Edit: I now realized, that the order of executing is not like I wanted. Why?

schylake
  • 434
  • 3
  • 14
J.Doe
  • 13
  • 2
  • `outside` part happens **BEFORE** `inside`. The variable is changed, you're just checking it too early. – zerkms Dec 11 '17 at 19:49
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Blue Dec 11 '17 at 19:49

2 Answers2

0

The issue is that navigator.geolocation.getCurrentPosition(succes, error) is asynchronous. It won't be called before your final console.log() just because it appears in the code before that statement. The the final console.log() runs before your success function returns and at that point, lat hasn't been assigned its value yet.

You can do what you are attempting, you just need to wait until success completes:

var lat = '';
var lon = '';
navigator.geolocation.getCurrentPosition(succes, error);

function succes(position){
    var crd = position.coords;
    lat = crd.latitude;
    lon = crd.longitude;
    
    // At this point, we know that the global variables have been 
    // assigned their values, so it's safe to access them:
    successIsDone();
}

function error(err){
    console.warn(err.code + ': ' + err.message);
}

function successIsDone(){
  console.log('latitude: '+ lat);
  console.log('longitude: '+ lon);  
}
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

navigator.geolocation.getCurrentPosition is most likely asynchronous, am I right? That means that console.log('outside: '+lat); gets executed before lat is assigned a value. You will have to use your variables after (or inside) success:

var lat = '';
var lon = '';
navigator.geolocation.getCurrentPosition(succes, error);

function succes(position){
    var crd = position.coords;
    lat = crd.latitude;
    console.log('inside: '+lat);
    doSomethingWithMyVariables();
}

function error(err){
    console.warn(err.code + ': ' + err.message);
}

function doSomethingWithMyVariables(){
    console.log('outside: '+lat);
}
Matt Spinks
  • 6,380
  • 3
  • 28
  • 47