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

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 ‘’ API.

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?

Here’s the link to my project.
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:


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

function gotData(data) {
function doMe(){

(function () {
  var ipinfoURL = "";
  $.getJSON(ipinfoURL, gotData)
1 Like

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.

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

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.

1 Like