i have the following code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(posi) {
var lat = posi.coords.latitude;
var lon = posi.coords.longitude;
console.log(lat);
}, showError);
} else {
$(".position").html("Geolocation is not supported by this browser");
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
alert(lat);
$(".weather").html("<p>" + lat + "</p>");
the problem is that at the alert(lat) at te bottom it says that it is undefined and at the start at the if condition the console.log(lat) works perfectly fine! what is wrong at the bottom? i have tried making global variables lon, lat before if but the same thing happens.
geolocationis asynchronous. You are trying to alert it before the data is returned. Consume it in the callback. Notice that the alert fires before theconsole.log()log(). That's how asynchronous operations work ... it takes time to send and receive the request