I am trying to use the following script to make an app which detects your current location and tells you the local weather:
var lat = 0;
var long = 0;
function showLocation(position) {
lat = position.coords.latitude;
lon =position.coords.longitude;
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
} else if ( err.code == 2) {
alert("Error: Position is unavailable!");
}
}
function getLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(showLocation, errorHandler);
}else{
alert("Sorry, browser does not support geolocation!");
}
}
var url = "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&APPID={myKey}";
In order to call the Weather API for receiving JSON info, I need to use the values of the lat and long variables from the showLocation() function. But outside the function, the variables still have the value "0".
Also, I want to use the values of the "city", "temp", "weatherStatus" and "country" outside the getJSON method.
var city="";
var temp="";
var weatherStatus="";
var country = "";
$.getJSON(url, function(json){
city = json.name;
temp = Math.round(json.main.temp-273.15);
weatherStatus = json.weather[0].description;
country = json.sys.country;
}
//alert(city) will be "undefined"
Thank you for your time!