Weather App - Using variable in place of url in $.getJSON

Weather App - Using variable in place of url in $.getJSON
0

#1

Hi there,

Been trying to figure this out for quite a while, hoping you all can help. I know more than one person has had headache with the Weather App due to CORS, but haven’t been able to figure out why I’m having this issue.

Basically my question is, why does this code work:

 $.getJSON("https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/weather?lat=42.2656762&lon=-71.018407&appid=09a7909c13b7ee77da5ec3cab4b6cd3f&units=metric", function(data) {
     $("#weather").html(data.main.temp);
          console.log(data);
});

But this code, which just replaces a static url for a variable called “link” does not work:

$(document).ready(function() {
  var link;
  var lat = "";
  var lon = "";
  
  if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
   link = "https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/weather?" + "lat=" + lat + '&lon=' + lon + "&appid=09a7909c13b7ee77da5ec3cab4b6cd3f&units=metric";
    console.log(link);
    
    
    
  });
}

$.getJSON(link, function(data) {
  $("#weather").html(data.main.temp);
  console.log(data);
          
  });
});

I did console.log(link) to check that it’s creating a proper link, which it is. And if I copy and paste the link result in place of the “link” variable in the .getJSON, it works. So shouldn’t calling “link” be the same thing? Here is the codepen.io link btw: https://codepen.io/ittakesii/pen/EXGrzW


#2

@ittakesii You are using both single’inverted commas’ and double inverted commas “” in ur link . Kindly use any one of them or more specifically single one . Hope this helps . :slight_smile:


#3

Thanks for catching that! It didn’t have an effect on the issue though, unfortunately.


#4

You’ll need to run your AJAX call in the getCurrentPosition callback.

navigator.geolocation.getCurrentPosition(function(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    link = "https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/weather?" + "lat=" + lat + '&lon=' + lon + "&appid=09a7909c13b7ee77da5ec3cab4b6cd3f&units=metric";

    $.getJSON(link, function(data) {
            $("#weather").html(data.main.temp);
            console.log(data);
        });
    });
});

#5

That did the trick, thank you!!

Can’t believe I didn’t try that. I tried that earlier when the issue was something else and I didn’t think to try that as a solution for this issue. I appreciate it.

Now I can move on to actually coding the app …