Background geolocation looks like a simple thing to implement, but now with hybrid app, such as Apache Cordova apps. This is because all JavaScript code execution in WebView will be stopped when you’ll “minimize” app or your device will go to sleep mode. But this can be solved by using the native apps or Cordova plugins. Today we’ll learn how to create a mobile app with background geolocation feature using Apache Cordova and one plugin.
- Install background geolocation plugin:
1 |
cordova plugin add cordova-plugin-mauron85-background-geolocation |
Simple use this plugin:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
document.addEventListener('deviceready', setupGeolocation, false); function setupGeolocation () { /** * This function will be executed every time a geolocation was got on the background. */ var callbackFn = function(location) { // Console.log only is here. You need to setup your own data interaction here console.log('[js] BackgroundGeoLocation callback: ' + location.latitude + ',' + location.longitude); /* IMPORTANT: You must execute the finish method here to inform the native plugin that you're finished, and the background-task may be completed. You must do this regardless if your HTTP request is successful or not. IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background. */ backgroundGeoLocation.finish(); }; /** * Error handler */ var failureFn = function(error) { console.log('BackgroundGeoLocation error'); }; // A lot of options is available here, you can see them all on plugin repo (see link below) backgroundGeoLocation.configure(callbackFn, failureFn, { desiredAccuracy: 10, stationaryRadius: 20, distanceFilter: 30, debug: true, // <-- Play sounds for background-geolocation life-cycle. Also will cause local notifications under iOS. stopOnTerminate: false, // <-- Clear background location settings when the app terminates }); // Start tracking of user coords backgroundGeoLocation.start(); // Stop tracking of user coords // backgroundGeoLocation.stop(); } |
For Ionic framework / AngularJS apps I’m strongly recommend you to use this as an Angular service, like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
app.factory('BackgroundGeolocationService', ['$q', '$http', function ($q, $http) { var callbackFn = function(location) { $http({ //request options to send data to server }); 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: 20, distanceFilter: 30, locationService: 'ANDROID_DISTANCE_FILTER', debug: false, stopOnTerminate: false }); backgroundGeoLocation.start(); }; return { start: start, // Initialize service and enable background geolocation by default init: function () { var bgGPS = window.localStorage.getItem('bgGPS'); if (bgGPS == 1 || bgGPS == null) { start(); } }, // Stop data tracking stop: function () { window.localStorage.setItem('bgGPS', 0); backgroundGeoLocation.stop(); } } }]); |
1 2 3 4 5 |
app.run(function($ionicPlatform, BackgroundGeolocationService) { $ionicPlatform.ready(function() { //For Ionic BackgroundGeolocationService.init(); }); }); |
Hello !
Thank you for this article. However, I encounter an issue with the Service solution : backgroundGeoLocation is undefined.
How do you access the plugin from a controller of your app ?
Thank you!
Benjamin
Hi,
You can access it if you’ll inject it as dependency, like
app.controller(‘myctrl’, [‘BackgroundGeolocationService’], ….
I am using your Ionic way. But I am getting an error Uncaught “ReferenceError: backgroundGeoLocation is not defined”. Is there something else to do?
I’m not sure this is in my scope of competence. The problem can be somewhere inside the plugin or it also can be inside the whatsapp. I can only suggest to somehow convert gif to jpg/png (for example using canvas or backend – I don’t know what is the best choice for you).
Sorry I didn’t get you. I was enquiring about the blog you wrote about “Background Geolocation With Apache Cordova”. Sorry if my question was not clear.
thank you SooooOoO very much.
this is great.
Can I get the location from GSM using this plugin if the GPS is turend off?
I’m not sure, please refer to plugin docs
HELLO I NEED TO TRACK THE POSITION OF USER IF THE APP IS CLOSED HOW CAN IT ?,PLEASE
The aricle is exactly about this
hello , i need to use Dbmeter plugin in background, is it possible to do it ?
I never heard about Dbmeter plugin
Thanks, Man. this is really helpful. you explained it much much better than official doc.
keep it up. Thanks again.
Bro..Will it work while app is closed? I think it is working only when the app gets “minimized“.
It should, at least author declares such ability
I am not able to use this plugin in my phonegap app. Please help.
Thanks
Help you yourself