Oumaya Abdelkhalek Oumaya Abdelkhalek - 2 months ago 44
AngularJS Question

cordova ionic framework : get location background service

I'm trying to get the current user location, but it changes when I reload code, even when I want to get the location every x seconds. This my solution:

app.controller('geoCtrl', function($scope, $timeout, $cordovaBackgroundGeolocation, $ionicPlatform, $window, $cordovaGeolocation)
{
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude
var long = position.coords.longitude
alert('lat='+lat);
alert('long='+long);
}, function(err) {
// error
});


var watchOptions = {
timeout : 3000,
enableHighAccuracy: false // may cause errors if true
};

var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
// error
},
function(position) {
var lat = position.coords.latitude
var long = position.coords.longitude
});


watch.clearWatch();

//-- End Geolocal
})


But this works only when I launch the application, please anyone have an idea ? To help me sychronise my application to get location data every x seconds :)

Answer

Probably what you want is this:

app.controller('GeoCtrl', function($cordovaGeolocation, $interval) {

  var posOptions = {
    timeout: 10000,
    enableHighAccuracy: false
  };

  var getLocation = function() {
    $cordovaGeolocation
      .getCurrentPosition(posOptions)
      .then(function(position) {
        // location coordinates
        console.log(position.coords);
      })
      .catch(function(err) {
        // handle error
        console.log(err)
      });
  };

  $interval(getLocation, 3000); // 3 seconds for now

});

Reference : ngCordova Geolocation docs

Comments