I'm working on a homework project to use an API to display the weather. Originally, I declared variables "latty" and "lonny" at the top of my script, in the a main function scope everything else was inside, and later they were set = to latitude and longitude using navigator.geolocation. After setting them to the coordinates I then tried to use them as part of the URL line that is sent to the API, but the values for latty and lonny never carried over. I thought declaring them in the parent function would allow them to be used in subsequent, nested functions. Since geolocation requires a function in order to get coordinates, I ended up having to nest the entire script within the getPosition() function in order to be able to use the values that it retrieves:
this.addEventListener("load", navigator.geolocation.getCurrentPosition(getPosition));
function getPosition(position) {
var latty = position.coords.latitude;
var lonny = position.coords.longitude;
var url = "https://api.darksky.net/forecast/";
var apiKey = '5a4ae697ea6b02e5a4ae697ea6b02e/';
weatherAjax();
function weatherAjax(){
$.ajax({
url: url + apiKey + latty + "," + lonny + degreeType,
dataType: 'jsonp',
success: function(data) {
$("#weatherID").html("<h1>" + Math.round(data.currently.temperature) + degreeSymbol + data.currently.summary + "</h1>");
}
});
}
Is there a better way to do this, without nesting everything within getPosition()? It seems strange that I cannot get information from geolocation, set those coordinates to a variable, and call them into another function. I couldn't figure out how to return that information, either, and I won't share that mess with you here because it was terrible.
I understand the basic idea of scope as: you can only access variables that are "higher up" in the nesting order. Sibling-level or child functions will not "share" variable access. Is this correct? Can this be improved upon?