1

I am looking for a way to force my javascript application to wait for the coordiantes before doing more code. I want the following command or something similar to be synchronous not asynchronous.

navigator.geolocation.getCurrentPosition(getGPSCoordinates);

I'm aware that I could just put my code in the callback function but is this the only way? Isn't there a way for me to just wait for it to finish and then make my decision?

Joseph Astrahan
  • 8,659
  • 12
  • 83
  • 154
  • Check out http://stackoverflow.com/questions/16823933/how-can-i-write-a-function-that-takes-x-amount-of-seconds/16823955#16823955 - synchronous operations will freeze UI for duration of operation, so not really something to wish for. Note that UI will be frozen from OS point of view too and it may trigger recovery from "non-responsive" app (whatever it is for browser/OS of your choice). – Alexei Levenkov Dec 14 '13 at 03:37
  • 1
    May we know why.. because it is a bad design to use a synchronous operation to do a remote data fetch.... – Arun P Johny Dec 14 '13 at 03:39
  • You shouldn't even attempt this. Depending on how the browser implements things, you may actually hang up the process parsing data from the GPS since you're not letting the thread run normally. It makes no sense to do this. There is never a good reason. – Brad Dec 14 '13 at 04:11

1 Answers1

2

Isn't there a way for me to just wait for it to finish and then make my decision?

It is not recommended to turn it to a synchronous operation because will freeze your UI during the request.

One of the solutions to wait for asynchronous function to finished it is to implement a callback function.

function getLocation(callback) {
     if (navigator.geolocation) {
       var lat_lng = navigator.geolocation.getCurrentPosition(function(position){
          var user_position = {};
          user_position.lat = position.coords.latitude; 
          user_position.lng = position.coords.longitude; 
          callback(user_position);
       });
     } else {
         alert("Geolocation is not supported by this browser.");
     }
}
getLocation(function(lat_lng){
    console.log(lat_lng);
});

Working solution.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128