So I've been having this issue for the past couple of hours. I'm trying to get a user's location by using the navigator object, and I'm able to get the lat and long just fine, but when I try to return it and use it as a variable for a Google Maps LatLng object, it returns as undefined.
Here is the code:
function getCurrentLat(){
var lat
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
alert(lat);
});
alert(lat);
}else{
console.log("Unable to access your geolocation");
}
return lat;
}
The first alert inside the getCurrentPosition function will show the correct latitude, however, the second one outside the function shows as undefined. How can I get the variable to show correctly outside of the getCurrentPosition() function?