0

I can't work out why console.log(latitude) isn't working outside of the if statement. I can recall latitude in the console so its value is being updated. My guess then is that console.log(latitude) is being run before latitude's value is changed but my solutions to ensure the if statement finishes first so far haven't worked. I've tried debugger too. Any help is much appreciated! (I hope I haven't overlooked something very simple!)

var latitude = "" ;
var longitude = "";

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      latitude = position.coords.latitude;
      longitude = position.coords.longitude;
      place.textContent = ("latitude: " + latitude + "  longitude: " + longitude);
    });
  }

  console.log(latitude);
leto
  • 489
  • 4
  • 18
  • because it is asynchronous. It is like ordering a delivery pizza, outside of it, you made the call and you try to eat it. – epascarello Feb 20 '18 at 16:51

1 Answers1

1

Callback is asynchronous. Hence the console.log for latitude would return you undefined. If you want to access latitude after your calculation (inside the callback) then you need to do your code snippet bit differently. Something like:

navigator.geolocation.getCurrentPosition(function(position) {
      latitude = position.coords.latitude;
      longitude = position.coords.longitude;
      place.textContent = ("latitude: " + latitude + "  longitude: " + longitude);
      fn(latitude,longitude)
    });

Then you can get the last calculated value inside the fn function:

fn(latitude,longitude) => {
   //use the logic here
}
Ant's
  • 13,545
  • 27
  • 98
  • 148