0

)

So I'm trying to learn about JavaScript and geolocation, but I've run into this, probably simple, problem:

let myLat; // Global

navigator.geolocation.getCurrentPosition((position) => {
    myLat = position.coords.latitude;
    console.log(myLat); // works
});

console.log(myLat); // undefined

I don't get why I cannot just use a global variable to hold the latitude-info?

  • because `getCurrentPosition` is asynchronous – Bravo Jul 09 '21 at 10:26
  • `getCurrentPosition` is an async process. JS will put it on the task queue, and then process the next statement. `myLat` doesn't exist until the the process has been resolved which is why the first log works, but the second doesn't. – Andy Jul 09 '21 at 10:27
  • https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Andy Jul 09 '21 at 10:29

0 Answers0