I just started building the weather app and wrote the code to get latitude and longitude . But it always shows it as undefined . Here is the code -
var latitude;
var longitude;
var got_location = true;
var error_message = "";
$(document).ready(function(){
getLocation();
if(got_location)
{
$("div").html("Latitude : "+latitude+"<br>Longitude : "+longitude);
}
else
{
$("div").html("Error : "+error_message);
}
});
function getLocation()
{
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(getCoordinates, getError);
}
else
{
got_location = false;
error_message = "Geolocation is not supported by this browser."
}
}
function getCoordinates(position)
{
latitude = position.coords.latitude;
longitude = position.coords.longitude;
}
function getError(error)
{
got_location = false;
switch(error.code)
{
case error.PERMISSION_DENIED:
error_message = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
error_message = "Location information is unavailable."
break;
case error.TIMEOUT:
error_message = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
error_message = "An unknown error occurred."
break;
}
}
Link - https://codepen.io/kshitij1234/pen/zwmJaM
I am guessing that is because the if condition gets evaluated before the function execution stops but why does this happen? How can I correct this? Also it would be wonderful if you could share some of your experience regarding correct practices of using functions and (document).ready .
Thank you in advance!!