How To Assign Global Variable Inside Of An Asynchronous Function In Javascript?
Console logging the lat returns undefined, while I want to assign the value of position.coords.latitude to it. What is the problem?
Solution 1:
You can't log there, you must need callback function to achieve your goal
<script>var x = document.getElementById("demo");
functiongetLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
functionshowPosition(position) {
console.log("Latitude: " + position.coords.latitude +" Longitude: " + position.coords.longitude)
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
Solution 2:
use callback function $(document).ready(function(){ var lat, lon;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat=position.coords.latitude;
lon=position.coords.longitude;
callbackFunction();
});
}
functioncallbackFuncton(){
console.log(lat);
//you can use your lat and lon here
}
});
Post a Comment for "How To Assign Global Variable Inside Of An Asynchronous Function In Javascript?"