Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make geolocation call synchronously in javascript

Im developing an app based on geolocation, so its mandatory to get the position in the first place, even before the execution of the rest of the app. So, how can I convert this module in a SYNCHRONOUS way????

 var geolocation = (function() {
 'use strict';

   var geoposition;

   var options = {
    maximumAge: 1000,
           timeout: 15000,
          enableHighAccuracy: false
};

function _onSuccess (position) {
    console.log('DEVICE POSITION');
    console.log('LAT: ' + position.coords.latitude + ' - LON: ' +  position.coords.longitude);
    geoposition = position
};

function _onError (error) {
    console.log(error)
};

function _getLocation () {
    navigator.geolocation.getCurrentPosition(
        _onSuccess,
        _onError, 
        options
    );
}

return {
    location: _getLocation  
}

}());

Thank you very much!

like image 805
Raul Vallespin Avatar asked Mar 05 '14 11:03

Raul Vallespin


Video Answer


1 Answers

Geolocation has to remain asynchronous, but you can achieve what you want by passing in a callback to your module's main function and calling it each in the success and error functions, after they have completed their processing:

var geolocation = (function() {
 'use strict';

   var geoposition;
   var options = {
     maximumAge: 1000,
     timeout: 15000,
     enableHighAccuracy: false
   };

   function _onSuccess (callback, position) {
     console.log('DEVICE POSITION');
     console.log('LAT: ' + position.coords.latitude + ' - LON: ' +  position.coords.longitude);
     geoposition = position
     callback();
   };

   function _onError (callback, error) {
     console.log(error)
     callback();
   };

   function _getLocation (callback) {
     navigator.geolocation.getCurrentPosition(
       _onSuccess.bind(this, callback),
       _onError.bind(this, callback), 
       options
     );
   }

  return {
    location: _getLocation  
  }

}());

geolocation.location(function () {
  console.log('finished, loading app.');
});

Fiddle

like image 119
Andy Avatar answered Oct 11 '22 15:10

Andy