Can't Set Global Scope

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));
});

The docs are going to be your best friend for understanding this problem. https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition

The getCurrentPosition method takes three parameters. The first parameter is a function to run if getCurrentPosition is successful, the second is a function to run if there is an error, and the third parameter is a set of options to pass into the getCurrentposition method. Both the second and third are optional. That being said. I would work on getting your success callback to work. Inside that function, write your getJSON function so you can use the lat and lng returns if successful.

I can get a vague sense of how this works, but I’m still unable to pass the values I want to global variables through the success function. I found a callback function online that solved that problem, but I don’t understand how it solved that problem.

The way freecodecamp presents this material is a little frustrating – they just give you something that works, but there’s not really much of an explanation of why it works. So I feel just going through their tutorials that my functional knowledge of javascript and why it works the way it works is really lacking – and then the challenges require you to develop that knowledge. But I would rather spend 50 hours acquiring that knowledge systematically as opposed to cobbling it together one piece of code after another. (/rant).

Can you explain to me why this doesn’t work?

crd = “Value not changed.”;

function success(pos) {
crd = pos.coords;
};

navigator.geolocation.getCurrentPosition(success);
alert(crd);

alert(crd) alerts me that the value has not changed.