Oumaya Abdelkhalek
Oumaya Abdelkhalek

Reputation: 329

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 :)

Upvotes: 3

Views: 866

Answers (2)

Prashant G
Prashant G

Reputation: 4900

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

Upvotes: 7

user3898336
user3898336

Reputation: 83

You can also use $cordovaGeolocation.watchPosition. You need not to manually apply $interval. But both the solution doesn't work in the case of backgroundApp.

Upvotes: 0

Related Questions