Here’s an old pen I wrote for people having this confusion and here’s something I wrote for someone having a similar problem. The example uses $.ajax but will work fine for $.getJSON.
I think that one thing you are not understanding is asynchronicity. You have two asynchronous functions in your code, the call to navigator.geolocation.getCurrentPosition and your ajax call.
These functions are requesting data and not waiting for an answer before they go on to the next code. The most basic way to handle this is with callback functions. You use a callback function in your ajax call (the success function) and you use one for you navigator call (showPosition). What these are saying are "go ahead and finish the rest of the program and just I’ll just call back to this callback function once I get my data back.
You have two asynchronous operations, one that depends on the other. The most basic way to handle that is to next them inside each other. So, I might have something like:
navigator.geolocation.getCurrentPosition(function(position) {
// manipulate variables if needed
$.ajax({
url:
"https://fcc-weather-api.glitch.me/api/current?lat=" + position.coords.latitude + "&lon=" + position.coords.longitude,
success: function(data) {
// use data object and send it to the screen
});
});
Does that make sense? The ajax call must be inside (or called from inside) the callback to the navigator call or the variable won’t be defined yet. In your original code, you get to the ajax call before navigator gets back so it doesn’t know what those variables are.
The whole asynchronous thing is extremely important in JavaScript. Most languages are synchronous (you execute in piece of code at a time and wait for it). Because JS utilized so many asynchronous resources, this would be inefficient. So, JavaScript is asynchronous, which is why you use so many callback functions, to deal with the asynchronicity.
I think you could get rid of some of those functions. Or you could use them in place of your anonymous callbacks - it’s a stylistic choice but in the beginning I found writing directly in an anonymous callback to be clearer.
Another observation: When you define your url string, you have “&&lon=” - there should be only one ampersand.
Let us know if any of this is confusing.