Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top