Saving navigator.geolocation in global variables

Hello. Can anyone explain why one cannot set a global variable to the values you get in the callback function from navigator.geolocation.getCurrentPosition( callbackFunction ); and how to go about using this values in the OpenWeather url in a more elegant way than nesting the function inside of the callback function for the navigator.geolocation function?

You see most people’s local weaather projects I’ve seen have either used the ip address api to get the location or used the navigator.geolocation as follows:

//Call the navigator.geolocation when document loads
$(document).ready(function() {
      navigator.geolocation.getCurrentPosition( geolocationCallback );  
 });

 //Write their callback function for the navigator.geolocation function
function geolocationCallback( position ){
  
   var latitude = position.coords.latitude;
   var longitude = position.coords.longitude;

  //The call another function to process the weather by using getJSON( api_url , weatherAPIcallback );
  getWeather( latitude, longitude );
}

I have seen this done in many solutions but there must be a more elegant/practical/organized way to go about it. Or is this good practice? Wouldn’t it be better to be able to manage all of this by beeing able to store the values as global variables and then writing independent callback functions for each API ( navigator.geolocation and open weather) ?

Anyone?

Guilty of doing this in all my intermediate projects, I was pretty relieved to see everyone else doing it . I assume the better way would be to have geolocator return an object (array?) with latitude and longitude, then use that object as argument for the JSON call, and I’m planning to do that when I confirm it’s actually the right way.

Edit: apparently that may not actually be possible so callback hell it is

It’s not the best, but it’s better than setting global variables, which you should avoid. A better idea would be to use one of the newer asynchronous mechanisms in JavaScript, like a promise, generator, or maybe an observable. At this point in your learning, Callback Hell is an acceptable practice, so just go with it.

2 Likes

Thank you so much I am reading the callback hell info you shared right now.