0

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!

  • How and when do you call `getLocation`? Both `getCurrentPosition` and `getJSON` are asynchronous functions, so you have to wait for the callback to be run before you can get the results. – Thilo Jan 08 '17 at 13:09
  • There seems to be typo related to the usage variables 'lon' and 'long'. Some places it is used as 'long' and in other places as 'lon' – S R Chaitanya Jan 08 '17 at 13:11

0 Answers0