Local Weather: OpenWeatherMap API fails to load

I am trying to obtain the weather from the OpenWeatherMap API. With my existing code, I obtain an error that says “Failed to load resource”. Here is the link to my existing code on codepen: https://codepen.io/Ag_Yog/pen/aymJQw. I have tried adding https://cors-anywhere.herokuapp.com/ to the beginning of the API link as well.

Thanks for any help.

Try using https://fcc-weather-api.glitch.me/ instead of openweather. It should work right away. You should also move the .ajax() call inside the geolocation callback function.

I was wondering why the .ajax() was supposed to go into the geolocation callback function. Does making the latitude and longitude global variables and implementing them in the .ajax() allow the same effect? Thanks for the guidance.

.getCurrentPosition and .ajax are asynchronous. The callback functions that you provide them are called some time later in your program (after the browser’s finished reading your code).

If you walk through your original code, first the code checks if the browser supports geolocation. If it does, it will get the current position. But it won’t return them immediately, so you provide a callback function that will be called back later, which describes what to do with the position data once that data is available.

After you’ve registered a geolocation callback function, your code will try to request some weather data via .ajax(). It will try to get some data from the URL that you provided, but at this point, the latitude and longitude variables are still empty (because the code that will provide them is waiting to be called back), and you’ll get an error.

By putting the .ajax() call inside the geolocation’s callback function, a weather request will not be made until the geolocation data is available.

1 Like