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.
Because
getCurrentPositionis an asynchronous call.You need to wait for the callback to fire before you can access the values it retrieves.