Global variable turns up undefined when assigned JSON data - Show the Local Weather

Global variable turns up undefined when assigned JSON data - Show the Local Weather
0

#1

Hey guys :slight_smile:

I just finished the “Show the local weather project”. The basic requirement is to show the current local weather using HTML5 geolocation or as some others have done; use an API for it. I’ve done the latter, using the ‘ipinfo.io/json’ API.

PROBLEM
I’m having a problem though with displaying the correct location and weather. The problem I think is with a variable named userRegion. I’ve tried to set userRegion as a global variable but it turns up “undefined”, evident from console.log(userRegion). Could someone please advice?

NOTES
Here’s the link to my project. https://codepen.io/surajr1711/pen/ZaGeoX/
I’ve tried to make it convenient for your review by commenting the jQuery with the following steps in respective areas.

//1. calling setup function to get geolocation.
//2. setup function gets geolocation using ipinfo API.
//3. API sends JSON data to gotData function.
//4. gotData function stores JSON location in userRegion global variable.
//5. PROBLEM! Why is userRegion “undefined”? :frowning:
//6. calling getWeather function which uses openweathermap API.
//7. getWeather function calls openweathermap API using userRegion global variable as the query but userRegion is "undefined.

Please have a look guys. Let me know what I’m doing wrong. What am I missing? :thinking:

Sincerely
Suraj


#2

because global variable is logged and the other functions fires before the variable userRegion stores anything. use your callback method gotData to execute functions after fetching the data
ref: http://api.jquery.com/jquery.getjson/

function gotData(data) {
  doMe.call(data)
}
function doMe(){
  console.dir(this)
}

(function () {
  var ipinfoURL = "https://ipinfo.io/json";
  $.getJSON(ipinfoURL, gotData)
})()

#3

You were right! It was executing before userRegion stored anything.
It works now… you’ve saved me a lot of time.
I’ve acknowledged you in the footer.
Thank you.


#4

me thinks that tis too much man :sweat_smile: no need for that really


#5

Thank you :slight_smile: I actually got stuck on this too. I was like, ‘why can I use the console and pull lat & long but it’s showing as undefined in my API call’. Thanks a ton! I knew it was a scoping issue just couldn’t figure out why.