Weather App: Cannot set global variables inside function. Please help

Weather App: Cannot set global variables inside function. Please help
0

#1

I am coming along with the weather app but for some reason when I try and set two global variables inside a function that gets the location, it doesn’t work.

var lati;
var long;

$.getJSON(‘http://ip-api.com/json’,
function (location){
lati = location.lat;
long = location.lon;
$(".location").html(location.city);
});

If I try and console lati or long they are blank.

I’ve tried setting the variables to the window object and it’s the same.

What am I doing wrong?

Would appreciate any help on this.

Thank you.

Codepen here http://codepen.io/joshpitzalis/pen/QKjxPm


#2

when your code runs it calls the $.getJSON… function … so it sends a request and waits for the result … its quick but the code is still running while this is happening so console.log of lati and long is executed but result is not back yet from the request when these lines are executed … these two lines need to be moved inside your $.getJSON function … in your case in your codepen put them after this line in your code $(".location").html(location.city); … you will then see the result in your console.

you then have another problem as you need these results for you request for open weathermap … but that will allready have being run while waiting for the first request for the lon and lati request is running.

what i did was create a function that enclosed the openweather map request and put a call for it at end of request for lon and lat … this way the call for openweather api only gets called after the results get back from the first request
eg … $.getJSON(url. function(location){
code
$(".location").html(location.city)
console.log(lon)
console.log(lati)
senOpenWeatherReq(lon, lati);
});

var sendOpenWeatherReq(x, y){
code
};
hope this helps


#3

@JohnL3 Thank you so much for taking the time to explain that. It helped a lot and now I understand callbacks. Finished the project http://codepen.io/joshpitzalis/pen/QKjxPm
Cheers!