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