0

So I was having problem with getting the longitude and latitude using the navigator.geolocation and storing it in a global variable. I used alerts at different places to check the flow of the javascript code. I found that the order to be 1, 2, 4 and 3. Why is that? I am really confused.

 $(document).ready( function() {
      var latitude;
      var longitude;
      alert('1');
      if(navigator.geolocation){
        alert('2');
            navigator.geolocation.getCurrentPosition( function(position){
              alert('3');
              latitude = position.coords.latitude;
              longitude = position.coords.longitude;
              geoCoords(latitude, longitude);


            });
         }

      alert('4');

    });
DazedNConfused
  • 189
  • 2
  • 13

1 Answers1

3

navigator.geolocation.getCurrentPosition is asynchronous - the function you pass into it as an argument is the callback function, which executes after getCurrentPosition has completed successfully. From the Mozilla docs:

navigator.geolocation.getCurrentPosition(success[, error[, options]])

The rest of the javascript code outside of the callback function will continue to execute without waiting for the callback function to run, which is why you see the order of 1, 2, 4, 3.

hackerrdave
  • 6,486
  • 1
  • 25
  • 29