I'm facing an issue with incorporating geolocation data into my $ajax call URL. Currently, both console.log(lat/lon) calls return the initial value of 0, indicating that the geolocation call is too late to provide the updated values. This results in the $ajax calls being made with default latitude and longitude values: "
var lat = 0;
var lon = 0;
console.log(lat);
console.log(lon);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(pos){
lat = pos.coords.latitude;
lon = pos.coords.longitude;
})
}
function getWeatherData() {
console.log(lat);
console.log(lon);
setTimeout(function(){
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=9011468f93d0dac073b28cda9e83cd01",
success: function (data) {
console.log(data);
},
error: function () {
console.log("REKT");
}
})
}, 1000);
}
$(document).ready(function () {
getWeatherData();
});
To resolve this, I added an arbitrary timeout function to the $ajax call. However, I am concerned about what would happen if the call takes longer than 1000 or 10000ms. Is there a more elegant solution to ensure that the $ajax call only executes after the geolocation code has finished running?