Background geolocation in Ionic app

This blog show an example on how to implement background geolocation in an Ionic app using the background geolocation plugin.  to capture user locations for building location aware applications

Install plugin

First add the cordova plugin to the Ionic app:

cordova plugin add cordova-plugin-mauron85-background-geolocation

Implement background geolocation service

Next, implement an Angular service:

var app = angular.module('starter');
app.factory('BackgroundGeolocationService', ['$q', '$http', function ($q, $http) { 
      var callbackFn = function(location) {
          postLocation(location);
          backgroundGeoLocation.finish();  
      },
      failureFn = function(error) {
          console.log('BackgroundGeoLocation error ' + JSON.stringify(error));  
      },

      //Enable background geolocation  
      start = function () {      
          //save settings (background tracking is enabled) in local storage    
          window.localStorage.setItem('bgGPS', 1);
          backgroundGeoLocation.configure(callbackFn, failureFn, {
               desiredAccuracy: 10,      
               stationaryRadius: 10,
               distanceFilter: 10,
               locationProvider: 'ANDROID_ACTIVITY_PROVIDER',
               interval: 10000,      
               fastestInterval: 5000,      
               stopOnStillActivity: false,
               debug: false,      
               stopOnTerminate: false
         });
         backgroundGeoLocation.start();
      };
     // Send location to a backend server, e.g. for location tracking
     postLocation = function post(location) {
         return $http(      
           {        
              method: 'POST',
              headers: {
                   "Content-Type": "application/json"
                    },
              url: 'http://<location server DNS>/location',
              data: {          
                    lat : location.latitude,
                    lng : location.longitude        
                    }      
           }).then(function (response) {
                   return response.data;      
           });  
       }
  
       return {    
            start: start,
            // Stop data tracking    
            stop: function () {
                window.localStorage.setItem('bgGPS', 0);
                backgroundGeoLocation.stop();    
            }  
      }
}]);

The codes above are largely based on this blog article.  I have modified the plugin configuration (see notes below). Details about each configuration parameter can be found in the plugin documentation. I am setting it up and tested for Android here. A few notes or tips below:

  1. Two location providers are supported in Android – Android_distance_filter_provider and Android_activity_provider. I end up using the 2nd one to adjust the intervals in which the app gets location update by setting the parameters interval and fastinterval (to 10 and 5 seconds respectively).
  2. Debug is your friend. Set this to true will trigger a sound and notification when the app receives a location update.
  3. I use a combination of parameters desiredAccuracy, stationaryRadius and distanceFilter to define how often the app should receive location update events. The values set here seems to strike a good balance between accuracy/frequency and battery usage but its largely depends on the app’s use cases and phones.
  4. The plugin includes a url paramter where you can set to the backend server to post the locations. It is also possible, and more flexible, to just implement your own method and call it in the callback function callbackFn 

To kick start the plugin, call init() method in the app.js :

angular.module('app', ['ionic', ...])
.run(function($ionicPlatform, $http, BackgroundGeolocationService) {
   $ionicPlatform.ready(function() {    
       if(window.StatusBar) {
          StatusBar.styleDefault();
       }
       BackgroundGeolocationService.init();
   });
});

Now the Ionic app can send geolocations events when it is in the background, it is rather straight forward to implement a backend server to track and display users’ current locations. Below is a screenshot of a Java app I build, for example:

blog_track.png