Help with what must be a stupid mistake but I can't find it

Hi there,

I’ve knocked together a first draft on the Weather project, to get the api part working. I had it working earlier, when I had function getWeather() set to retrieve data on a button click.

Now I have gotten rid of the button click, because I want the data retrieved on document.ready. But the function getWeather() is not working anymore. It’s as if the global variables aren’t global anymore.

I would appreciate a fresh set of eyes looking at this, to see what I’ve done wrong.

Thank you!

My code:

You should call getWeather from inside the geolocation callback, and immediately pass it the URL that you’ve constructed there.

Yeah, it’s as if the global variables aren’t global anymore. It’s because both getting the location and requesting for weather data are asynchronous, and they tend to be needed to “chain” together in order to work properly.

1 Like

Hey. The .getCurrentPosition method is asynchronous. You’ll need to call your getWeather() function inside the method’s success callback like so:

navigator.geolocation.getCurrentPosition(function(position) {
  lat = position.coords.latitude;
  long = position.coords.longitude;
  url = "https://fcc-weather-api.glitch.me/api/current?lat="+lat+"&lon="+long;
  getWeather(url);
});

Then, you’ll only need to reference your getLoc function in the .ready jQuery method:

$(document).ready(getLoc);

Thank you, kevomedia and noyb - your corrections make it work.

But, for my education, is there no way to store the result of asynchronous calls like getCurrentPosition or the call to retrieve the JSON data in a variable, such that they can be used later?

Thanks, that makes sense. I appreciate your taking time to explain it this way.