Good Morning,
I'm having some trouble with the following function.
function getLocation() {
var geoLat;
var geoLong;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(geo) {
geoLat = geo.coords.latitude;
geoLong = geo.coords.longitude;
console.log(geoLat);
});
} else {
alert("Geolocation information is required for this app to function correctly");
return false;
};
console.log(geoLat);
return {
lat: geoLat,
long: geoLong
};
};
The first console.log(geoLat)
in the if statement returns the correct latitude assigned above it. When I try and reference the geoLat
variable again just before the final return
it is now undefined
. How can an assigned variable change it's value back to undefined
without me assigning it or clearing it?
I'm sure this is just me making some form of syntax error. I'm learning JS and don't understand this.
Thanks.
Edit: Now that I've had my mind blown with a 4th dimesion of aync functions I've changed it but still have the following problem
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(geo) {
var test = geo.coords.latitude;
console.log(test);
console.log(geo.coords.latitude);
return test;
});
} else {
alert("Geolocation information is required for this app to function correctly");
return false;
};
};
So console.log(test)
returns correct coords as does console.log(geo.coords.latitude)
, however return test;
still returns udefined
. I'm guessing the result
doesn't wait for the async function to finish?