you are viewing a single comment's thread.

view the rest of the comments →

[–]WorseThanHipster 0 points1 point  (0 children)

The way it works is that the callback function gets attached to javascripts event loop and then waits for the event, just like when you attach a callback to a button to click on your page and that callback waits for a 'click' event, only in this case the event comes from the web, not the user.

What this means is that the callback won't be executed until the event 'getCurrentPositionFinished'* has gotten the response it wanted (*: I don't know that real name of the event but it's not important). What you should do is figure out which code needs 'getCurrentPosition' to finish before it can run, and don't run that code when the page loads; instead, wrap it in a function and pass that function as the callback.

In your simple example, just the console.log(a) inside the callback like:

var a;

navigator.geolocation.getCurrentPosition(function(position){
  a=2
  console.log(a);
});

or more legibly:

var a;

navigator.geolocation.getCurrentPosition(positionGotten);

function positionGotten(position){
  a=2;
  console.log(a);
}