I’m working on the Weather API App, and I’m having trouble with variable scope. I can get this to work fine:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
latitude = parseFloat(Math.floor(position.coords.latitude));
longitude = parseFloat(Math.floor(position.coords.longitude));
url =
“https://fcc-weather-api.glitch.me/api/current?lat=” +
latitude +
"&lon=" +
longitude;
$.getJSON(url, function(json) {
$("#message").html(JSON.stringify(json));
});
});
}
But when I move the JSON request outside of the scope of the “if” statement, the variables I need no longer have values. I’ve tried to make them global using window.variable, and as far as I can tell they should be global already given the way I declared them. Any idea why this is happening? Just to be precise, this is what isn’t working:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
latitude = parseFloat(Math.floor(position.coords.latitude));
longitude = parseFloat(Math.floor(position.coords.longitude));
url =
“https://fcc-weather-api.glitch.me/api/current?lat=” +
latitude +
"&lon=" +
longitude;
});
}
$.getJSON(url, function(json) {
$("#message").html(JSON.stringify(json));
});