Weather App - can't get JSON from API call, what is wrong in my code?

Weather App - can't get JSON from API call, what is wrong in my code?
0.0 0

#1

Hi everyone,

I’m working on the Weather App, this is my code:

var lat;
var long;

$(document).ready(function() {

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition (function(position) {
        lat= position.coords.latitude;
        long= position.coords.longitude;
    });
}

var url = 'https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139';
var urlApi = 'https://fcc-weather-api.glitch.me/api/current?lat='+ lat + '&lon='+ long + '.json';


$("#getWeather").on("click", function(){
    $.getJSON(urlApi, function(json) {
    $(".prova").html(JSON.stringify(json));
    });
});

});

What I wan to do here is:

  • using the geolocation to store latitude and longitude in two global variables.
  • using the fcc-weather-api to show the JSON in a div with the class “prova”.

I’m sure that there must be some big mistake in the code, probably due to misunderstandings about how JSON works. But so far I could not find out where it is.
Help would be much appreciated!
It is not that much about making the app, but about understanding what I’m doing wrong :slight_smile:

Thank you!


#2

I did 2 things to make this work.

First, I moved everything after the geolocation block into the getCurrentPosition call (everything from var url... to the end of $('#getWeather).on...).

Second, I removed + '.json' from the end of urlApi.

I also moved some global variables into the jQuery ready function. Not sure if this is required, but it is good practice.

Here’s my updated code block.

$(document).ready(function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var lat = position.coords.latitude;
      var long = position.coords.longitude;

      var url = "https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139";
      var urlApi =
        "https://fcc-weather-api.glitch.me/api/current?lat=" +
        lat +
        "&lon=" +
        long;
      
      $.getJSON(urlApi, function(json) {
        console.log(json);
      });

      // $("#getWeather").on("click", function() {
      //   $.getJSON(urlApi, function(json) {
      //     $(".prova").html(JSON.stringify(json));
      //   });
      // });
    });
  }
});

#3

Thanks a lot for your help Dave!

It was most helpful: now it works, plus I didn’t know that it was a good practice to keep the global variables within the j Query ready function.


#5

Thank you for your answer SkyC!
Ok, I think that now I’m understanding even more about what’s happening here.
So, if I got it right, the problem is that for instance for navigator.geolocation it takes some time for the browser to process it, so if I write the code like I did the browser will run through the next functions before being able to return the data from navigator.geolocation, is that it?