Background Geolocation
This plugin provides foreground and background geolocation with battery-saving "circular region monitoring" and "stop detection". For more detail, please see https://github.com/mauron85/cordova-plugin-background-geolocation
Repo: https://github.com/mauron85/cordova-plugin-background-geolocation
Installation
- Install the Cordova and Ionic Native plugins:
$ ionic cordova plugin add cordova-plugin-mauron85-background-geolocation $ npm install --save @ionic-native/background-geolocation
- Add this plugin to your app's module
Supported platforms
- Android
- iOS
Usage
BackgroundGeolocation must be called within app.ts and or before Geolocation. Otherwise the platform will not ask you for background tracking permission.
import { BackgroundGeolocation, BackgroundGeolocationConfig, BackgroundGeolocationResponse } from '@ionic-native/background-geolocation';
constructor(private backgroundGeolocation: BackgroundGeolocation) { }
...
const config: BackgroundGeolocationConfig = {
desiredAccuracy: 10,
stationaryRadius: 20,
distanceFilter: 30,
debug: true, // enable this hear sounds for background-geolocation life-cycle.
stopOnTerminate: false, // enable this to clear background location settings when the app terminates
};
this.backgroundGeolocation.configure(config)
.subscribe((location: BackgroundGeolocationResponse) => {
console.log(location);
// 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.
this.backgroundGeolocation.finish(); // FOR IOS ONLY
});
// start recording location
this.backgroundGeolocation.start();
// If you wish to turn OFF background-tracking, call the #stop method.
this.backgroundGeolocation.stop();
Instance Members
LocationProvider
Set location service provider @see https://github.com/mauron85/cordova-plugin-background-geolocation/wiki/Android-providers
Possible values: ANDROID_DISTANCE_FILTER_PROVIDER: 0, ANDROID_ACTIVITY_PROVIDER: 1
Accuracy
Desired accuracy in meters. Possible values [0, 10, 100, 1000]. The lower the number, the more power devoted to GeoLocation resulting in higher accuracy readings. 1000 results in lowest power drain and least accurate readings.
Possible values: HIGH: 0 MEDIUM: 10 LOW: 100 PASSIVE: 1000
enum {number}
Mode
Used in the switchMode function
Possible values: BACKGROUND: 0 FOREGROUND: 1
configure(options)
Configure the plugin.
Param | Type | Details |
---|---|---|
options |
BackgroundGeolocationConfig
|
options An object of type Config |
Returns: Observable<BackgroundGeolocationResponse>
start()
Turn ON the background-geolocation system. The user will be tracked whenever they suspend the app.
Returns: Promise<any>
stop()
Turn OFF background-tracking
Returns: Promise<any>
finish()
Platforms:iOS
Inform the native plugin that you’re finished, the background-task may be completed
Returns: Promise<any>
changePace(isMoving)
Platforms:iOS
Force the plugin to enter “moving” or “stationary” state
Param | Type | Details |
---|---|---|
isMoving |
boolean
|
Returns: Promise<any>
setConfig(options)
Setup configuration
Param | Type | Details |
---|---|---|
options |
BackgroundGeolocationConfig
|
Returns: Promise<any>
getStationaryLocation()
Platforms:iOS
Returns current stationaryLocation if available. null if not
Returns: Promise<Location>
onStationary()
Platforms:iOS
Add a stationary-region listener. Whenever the devices enters “stationary-mode”, your #success callback will be executed with #location param containing #radius of region
Returns: Promise<any>
isLocationEnabled()
Platforms:Android
Check if location is enabled on the device
Returns: Promise<number>
Returns a promise with int argument that takes values 0, 1 (true).
showAppSettings()
Display app settings to change permissions
showLocationSettings()
Display device location settings
watchLocationMode()
Platforms:Android
Method can be used to detect user changes in location services settings. If user enable or disable location services then success callback will be executed. In case or error (SettingNotFoundException) fail callback will be executed.
Returns: Promise<boolean>
stopWatchingLocationMode()
Platforms:Android
Stop watching for location mode changes.
Returns: Promise<any>
getLocations()
Platforms:Android
Method will return all stored locations. Locations are stored when:
- config.stopOnTerminate is false and main activity was killed by the system or
- option.debug is true
Returns: Promise<any>
getValidLocations()
Method will return locations, which has not been yet posted to server. NOTE: Locations does contain locationId.
Returns: Promise<any>
deleteLocation(locationId)
Platforms:Android
Delete stored location by given locationId.
Param | Type | Details |
---|---|---|
locationId |
number
|
Returns: Promise<any>
deleteAllLocations()
Platforms:Android
Delete all stored locations.
Returns: Promise<any>
switchMode(modeId)
Platforms:iOS
Normally plugin will handle switching between BACKGROUND and FOREGROUND mode itself. Calling switchMode you can override plugin behavior and force plugin to switch into other mode.
In FOREGROUND mode plugin uses iOS local manager to receive locations and behavior is affected by option.desiredAccuracy and option.distanceFilter. In BACKGROUND mode plugin uses significant changes and region monitoring to receive locations and uses option.stationaryRadius only.
BackgroundGeolocation.Mode.FOREGROUND BackgroundGeolocation.Mode.BACKGROUND *
Param | Type | Details |
---|---|---|
modeId |
number
|
Returns: Promise<any>
getLogEntries()
Return all logged events. Useful for plugin debugging. Parameter limit limits number of returned entries. @see https://github.com/mauron85/cordova-plugin-background-geolocation/tree/v2.2.1#debugging for more information.
@param limit {number} Limits the number of entries
Returns: Promise<any>
BackgroundGeolocationResponse
Param | Type | Details |
---|---|---|
locationId |
number
|
ID of location as stored in DB (or null) |
serviceProvider |
string
|
Service provider |
debug |
boolean
|
true if location recorded as part of debug |
time |
number
|
UTC time of this fix, in milliseconds since January 1, 1970. |
latitude |
number
|
latitude, in degrees. |
longitude |
number
|
longitude, in degrees. |
accuracy |
number
|
estimated accuracy of this location, in meters. |
speed |
number
|
speed if it is available, in meters/second over ground. |
altitude |
number
|
altitude if available, in meters above the WGS 84 reference ellipsoid. |
altitudeAccuracy |
number
|
accuracy of the altitude if available. |
bearing |
number
|
bearing, in degrees. |
coords |
Coordinates
|
A Coordinates object defining the current location |
timestamp |
number
|
A timestamp representing the time at which the location was retrieved. |
BackgroundGeolocationConfig
Param | Type | Details |
---|---|---|
desiredAccuracy |
number
|
Desired accuracy in meters. Possible values [0, 10, 100, 1000]. The lower the number, the more power devoted to GeoLocation resulting in higher accuracy readings. 1000 results in lowest power drain and least accurate readings. @see Apple docs (https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/index.html#//apple_ref/occ/instp/CLLocationManager/desiredAccuracy) |
stationaryRadius |
number
|
Stationary radius in meters. When stopped, the minimum distance the device must move beyond the stationary location for aggressive background-tracking to engage. |
debug |
boolean
|
When enabled, the plugin will emit sounds for life-cycle events of background-geolocation! See debugging sounds table. (optional) |
distanceFilter |
number
|
The minimum distance (measured in meters) a device must move horizontally before an update event is generated. @see Apple docs. (https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/CLLocationManager/CLLocationManager.html#//apple_ref/occ/instp/CLLocationManager/distanceFilter) |
stopOnTerminate |
boolean
|
IOS, ANDROID ONLY Enable this in order to force a stop() when the application terminated (e.g. on iOS, double-tap home button, swipe away the app).o Defaults to true (optional) |
startOnBoot |
boolean
|
ANDROID ONLY Start background service on device boot. Defaults to false (optional) |
startForeground |
boolean
|
ANDROID ONLY If false location service will not be started in foreground and no notification will be shown. Defaults to true (optional) |
interval |
number
|
ANDROID ONLY When using BackgroundGeolocation.LocationProvider.ANDROID_DISTANCE_FILTER_PROVIDER: The minimum time interval between location updates in milliseconds. (optional) |
notificationTitle |
string
|
ANDROID ONLY Custom notification title in the drawer. (optional) |
notificationText |
string
|
ANDROID ONLY Custom notification text in the drawer. (optional) |
notificationIconColor |
string
|
ANDROID ONLY The accent color to use for notification. Eg. #4CAF50. (optional) |
notificationIconLarge |
string
|
ANDROID ONLY The filename of a custom notification icon. See android quirks. NOTE: Only available for API Level >=21. (optional) |
notificationIconSmall |
string
|
ANDROID ONLY The filename of a custom notification icon. See android quirks. NOTE: Only available for API Level >=21. (optional) |
locationProvider |
number
|
ANDROID ONLY Set location service provider @see wiki (https://github.com/mauron85/cordova-plugin-background-geolocation/wiki/Android-providers) (optional) |
activityType |
string
|
IOS ONLY [AutomotiveNavigation, OtherNavigation, Fitness, Other] Presumably, this affects iOS GPS algorithm. @see Apple docs for more information (https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/CLLocationManager/CLLocationManager.html#//apple_ref/occ/instp/CLLocationManager/activityType) (optional) |
pauseLocationUpdates |
boolean
|
IOS ONLY Pauses location updates when app is paused Defaults to true (optional) |
url |
string
|
Server url where to send HTTP POST with recorded locations (optional) |
syncUrl |
string
|
Server url where to send fail to post locations (optional) |
syncThreshold |
number
|
Specifies how many previously failed locations will be sent to server at once Defaults to 100 (optional) |
httpHeaders |
any
|
Optional HTTP headers sent along in HTTP request (optional) |
saveBatteryOnBackground |
boolean
|
IOS ONLY Switch to less accurate significant changes and region monitory when in background (default) Defaults to 100 (optional) |
maxLocations |
number
|
Limit maximum number of locations stored into db Defaults to 10000 (optional) |
fastestInterval |
number
|
ANDROID ONLY with BackgroundGeolocation.LocationProvider.ANDROID_ACTIVITY_PROVIDER Fastest rate in milliseconds at which your app can handle location updates. (optional) |
activitiesInterval |
number
|
ANDROID ONLY with BackgroundGeolocation.LocationProvider.ANDROID_ACTIVITY_PROVIDER Rate in milliseconds at which activity recognition occurs. Larger values will result in fewer activity detections while improving battery life. (optional) |
stopOnStillActivity |
boolean
|
ANDROID ONLY with BackgroundGeolocation.LocationProvider.ANDROID_ACTIVITY_PROVIDER stop() is forced, when the STILL activity is detected (default is true) (optional) |