For the weather app project, I’m trying to store the latitude and longitude coordinates obtained from the navigator.geolocation.getCurrentPosition callback function into global variables.
I’m able to get the coordinate values but when they are assigned to the global variables, the global variables keep remain unassigned. Anyone know what I’m doing wrong?
var latitude = 0;
var longitude = 0;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
// confirmed that position.coords.latitude and position.coords.longitude return non-zero values
});
}
// latitude and longitude values remain zero
The concept of “promises” hasn’t been introduced by FreeCodeCamp for the weather app project. Is there no way to run the code outside of the callback function without them? In other words, it’s expected to run all the code from within the callback function? I wanted to write “cleaner” code by separate them into functions but that is not possible?
FreeCodeCamp won’t introduce promises at all (at least not before curriculum expansion, which will happen maybe next year), so you should go ahead and learn them by yourself - it is well worth it.
You could call a function with latitude and longitude as parameters from the callback and get rid of global variables.
latitude and longitude don’t remain zero forever :
var latitude = 0;
var longitude = 0;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
// confirmed that position.coords.latitude and position.coords.longitude return non-zero values
});
}
setInterval(function() {
console.log(latitude, longitude)
}, 1000) //=> console logging latitude and longitude every second
// at first, it logs zero values, then non-zero values
You don’t have to write the callback code within getCurrentPosition :
function callback(position) {
console.log(position.coords.latitude);
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(callback);
}