Weather App: How to use API data to generate a url for a second API?

Hi everyone!

I’m sooo close. Please help.

All I need to do is update latitude and longitude variables for the users location, so I can use these to build the url for the API request to Open Weather App.

Geolocation is down in chrome, so I’m trying to use a second API to get location based on IP (“http://ip-api.com/json”)

THE PROBLEM IS, when I use this first API I am unable to get the latitude and longitude variables to update outside of the function… Can anyone help?

Here’s some code snippets;

var getLocation = function(obj) {
    var lat = obj.lat;
    var lon = obj.lon;  
};

var url = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=" + APPID;

$(document).ready(function() {
    $.getJSON("http://ip-api.com/json", getLocation);
    $.getJSON(url, updateLocal);
});

You might have to make the second JSON call inside the getLocation function. Like

// But then the name `getLocation` doesn't fit anymore...
var getLocation = function(obj) {
  var lat = obj.lat;
  var lon = obj.lon;

  var url = "http://...";
  $.getJSON(url, updateLocal);
}

$(document).ready(function() {
  $.getJSON("http://ip-api.com/json", getLocation);
});
1 Like

Thanks!! It worked.

Was my issue happening because API calls happen slower than the code I wrote is executed? So that the information needed for the second API call wasn’t yet ready when I made the second JSON request?

Is this related to the ‘asynchronous’ business I am reading about?

Yes, that’s exactly it :slight_smile:

Your code doesn’t wait for the getJSON to return before continuing, and even though it only takes a split second to return the data from the API, your code has already moved on :slight_smile:

1 Like

According to what I’ve watched, callback functions to API calls (or anything else async) execute last, after the rest of the code has been executed. The order in which these callbacks are called vary.

so what I still don’t get is where’s the punch line? I understand that JS will continue with execution of the code in the stack even if the info from say an API call isn’t available.

What I don’t get is how to make my code wait for essential information that is needed and is not available until the API info is obtained.

I’ve tried setTimeout… didnt’ work.
i’ve tried do while loops which results in chrome crash.

beyond understanding what’s going on, how do I make sure my code doesn’t proceed on when it doesn’t have info it needs from an API call?

I recommend you to look into Promises.

With promises you are creating a function which returns promise to return something later :wink:

Quick codepen example:

ouch. made my head hurt… :sunglasses: