1

I'm just trying to get variables out of the geolocation.getCurrentPosition function from HTML5. However, I'm having a lot of difficulties getting my variables to be defined outside of the function.

The function works using the code below:

<script>
var latitude;
var longitude;
var accuracy;
var altitude;
var altitudeAccuracy;
var heading;
var speed;

if (navigator.geolocation){
  navigator.geolocation.getCurrentPosition(  
    function (position) {
      latitude = position.coords.latitude;
      longitude = position.coords.longitude;
      alert(longitude)
      accuracy = position.coords.accuracy;
      altitudeAccuracy = position.coords.altitudeAccuracy;
      heading = position.coords.heading;
      speed = position.coords.speed;
    }
  );
}

// alert(latitude);

Here I see the alert(longitude) return a numerical value. However when I comment that line out, and uncomment alert(latitude) -- I get an "undefined" alert.

Any help would be greatly appreciated! Thanks.

0

2 Answers 2

4

Because getCurrentPosition is an asynchronous call.

You need to wait for the callback to fire before you can access the values it retrieves.

function nextStep(){
    alert(latitude);
}

navigator.geolocation.getCurrentPosition(  
    function (position) {
      latitude = position.coords.latitude;
      longitude = position.coords.longitude;
      alert(longitude)
      accuracy = position.coords.accuracy;
      altitudeAccuracy = position.coords.altitudeAccuracy;
      heading = position.coords.heading;
      speed = position.coords.speed;
      nextStep();
    }
);
Sign up to request clarification or add additional context in comments.

Comments

1

getCurrentPosition is an asynchronous call

In javascript concurrency works with a "run to completion" model. That means that all code in the current function will complete before it moves on to the next execution context. In your original code, the code will execute in this order:

  • variable definitions
  • getCurrentPosition initialized
  • alert(latitude)
  • script completes

and then it will move on to the next execution context and run your callback function, at which time the variables will be set and the other alert will be run. You'll need to run your alert in the callback if you want to ensure that the variables have been set first

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.