[Solved]Local Weather Challenge: passing variable between two functions?

[Solved]Local Weather Challenge: passing variable between two functions?
0

#1

Hi everyone,

I’m struggling a little bit passing a variable between two functions (I think) in the Local Weather Challenge.
For some reason, $.getJSON is not reading the “url” variable updated in the function getting the coordinates.
Here is my code:

$(document).ready(function(){ 
  
 var latitude, longitude, url;
  
  //if geolocation, get coordinates, store in url variable
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
      latitude = position.coords.latitude;
      longitude = position.coords.longitude;
      url = "https://fcc-weather-api.glitch.me/api/current?lat="+latitude+"&lon="+longitude;
      });
    
  //get values from request url and add them to html
      $.getJSON(url, function(data){
      $(".main-list").append("<li><img src="+data.weather[0].icon+"</img></li>");
      $(".main-list").append("<li>"+data.name+"</li>");
      $(".main-list").append("<li>"+data.weather[0].main+"</li>");
      $(".main-list").append("<li>"+data.main.temp+"</li>");

      $(".desc").append("<li>"+data.weather[0].description+"</li>");
      $(".extended-list").append("<li>"+data.main.temp_min+"</li>");
      $(".extended-list").append("<li>"+data.main.temp_max+"</li>");
      $(".extended-list").append("<li>"+data.main.humidity+"</li>");
      $(".extended-list").append("<li>"+data.wind.speed+"</li>");
      });
    }
});

Many thanks in advance!


#2

navigator.geolocation.getCurrentPosition is asynchronous, so $.getJSON runs before url is updated.

To fix it, just put your $.getJSON directly after url = "https://fcc-weather....." (within function(position){}).


#3

Many thanks Ben, it now works perfectly!


#4

Can you point me in the right direction to learn about “asynchronous” I’m trying to understand it but it’s driving me crazy