Weather App - How to set global variables from a callback function?

Weather App - How to set global variables from a callback function?
0.0 0

#1

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

#2

Welcome to the asynchronous world. :slight_smile:

The problem is that you want something before it’s there. You should either work within your callback function or use promises to access the location.


#3

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?


#4

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.


#5

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

#6

I see well thanks. I’ll try to adjust my code to take into consideration this timing issue.