Need help upgrading to Ionic Framework 4.0? Get assistance with our Enterprise Migration Services EXPLORE NOW

Background Geolocation

Improve this doc

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

  1. Install the Cordova and Ionic Native plugins:
    $ ionic cordova plugin add cordova-plugin-mauron85-background-geolocation@alpha
    $ npm install --save @ionic-native/background-geolocation@4
    
  2. Add this plugin to your app's module

Supported platforms

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

code

message

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 (SettingNotFoundException) fail callback will be executed.

Returns: Observable<number>

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:

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(limit)

Return all logged events. Useful for plugin debugging. Parameter limit limits number of returned entries.

Param Type Details
limit number

Limits the number of entries

Returns: Promise<any>

getConfig()

Return all logged events. Useful for plugin debugging. Parameter limit limits number of returned entries.

Returns: Promise<any>

getCurrentLocation(options)

One time location check to get current location of the device. {timeout: Maximum time in milliseconds device will wait for location, maximumAge: Maximum age in milliseconds of a possible cached location that is acceptable to return; enableHighAccuracy: if true and if the device is able to provide a more accurate position, it will do so}

Param Type Details
options BackgroundGeolocationCurrentPositionConfig

Returns: Promise<any>

checkStatus()

Check status of the service

startTask()

Platforms:IOS 

Start background task (iOS only)

To perform any long running operation on iOS you need to create background task IMPORTANT: task has to be ended by endTask

Returns: Promise<number> taskKey

endTask()

Platforms:IOS 

End background task indentified by taskKey (iOS only)

headlessTask(func)

A special task that gets executed when the app is terminated, but the plugin was configured to continue running in the background (option stopOnTerminate: false).

In this scenario the Activity was killed by the system and all registered event listeners will not be triggered until the app is relaunched.

Param Type Details
func

forceSync()

Force sync of pending locations. Option syncThreshold will be ignored and all pending locations will be immediately posted to syncUrl in single batch.

Platform: Android, iOS

on(event, callbackFn)

Register event listener.

Triggered when server responded with “285 Updates Not Required” to post/sync request.

Param Type Details
event
callbackFn

removeAllListeners()

Unregister all event listeners for given event.

If parameter event is not provided then all event listeners will be removed.

BackgroundGeolocationResponse

Param Type Details
id number

ID of location as stored in DB (or null)

provider BackgroundGeolocationNativeProvider

Native provider reponsible for location.

Possible values: "gps", "network", "passive" or "fused"

locationProvider BackgroundGeolocationLocationProvider

Configured location provider.

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.

Note: Not all providers are capable of providing speed. Typically network providers are not able to do so.

altitude number

Altitude if available, in meters above the WGS 84 reference ellipsoid.

bearing number

Bearing, in degrees.

isFromMockProvider boolean

True if location was recorded by mock provider. (ANDROID ONLY)

Note: this property is not enabled by default! You can enable it "postTemplate" configure option.

(optional)
mockLocationsEnabled boolean

True if device has mock locations enabled. (ANDROID ONLY)

Note: this property is not enabled by default! You can enable it "postTemplate" configure option.

(optional)

BackgroundGeolocationConfig

Param Type Details
locationProvider number

Set location provider

Platform: all Available providers: DISTANCE_FILTER_PROVIDER, ACTIVITY_PROVIDER RAW_PROVIDER

(optional)
desiredAccuracy number

Desired accuracy in meters.

Platform: all Provider: all Possible values: HIGH_ACCURACY, MEDIUM_ACCURACY, LOW_ACCURACY, PASSIVE_ACCURACY Note: Accuracy has direct effect on power drain. Lower accuracy = lower power drain.

(optional)
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. Platform: all Provider: DISTANCE_FILTER

(optional)
debug boolean

When enabled, the plugin will emit sounds for life-cycle events of background-geolocation! See debugging sounds table.

Platform: all Provider: all

(optional)
distanceFilter number

The minimum distance (measured in meters) a device must move horizontally before an update event is generated.

Platform: all Provider: DISTANCE_FILTER, RAW

(optional)
stopOnTerminate boolean

Enable this in order to force a stop() when the application terminated. E.g. on iOS, double-tap home button, swipe away the app.

Platform: all Provider: all

(optional)
startOnBoot boolean

Start background service on device boot.

Platform: Android Provider: all

(optional)
interval number

The minimum time interval between location updates in milliseconds.

Platform: Android Provider: all

(optional)
fastestInterval number

Fastest rate in milliseconds at which your app can handle location updates.

Platform: Android Provider: ACTIVITY

(optional)
activitiesInterval number

Rate in milliseconds at which activity recognition occurs. Larger values will result in fewer activity detections while improving battery life.

Platform: Android Provider: ACTIVITY

(optional)
stopOnStillActivity boolean (optional)
notificationsEnabled boolean

Enable/disable local notifications when tracking and syncing locations.

Platform: Android Provider: all

(optional)
startForeground boolean

Allow location sync service to run in foreground state. Foreground state also requires a notification to be presented to the user.

Platform: Android Provider: all

(optional)
notificationTitle string

Custom notification title in the drawer.

Platform: Android Provider: all

(optional)
notificationText string

Custom notification text in the drawer.

Platform: Android Provider: all

(optional)
notificationIconColor string

The accent color (hex triplet) to use for notification. Eg. #4CAF50.

Platform: Android Provider: all

(optional)
notificationIconLarge string

The filename of a custom notification icon.

Platform: Android Provider: all

(optional)
notificationIconSmall string

The filename of a custom notification icon.

Platform: Android Provider: all

(optional)
activityType string

Activity type. Presumably, this affects iOS GPS algorithm.

Possible values: "AutomotiveNavigation", "OtherNavigation", "Fitness", "Other"

Platform: iOS Provider: all

(optional)
pauseLocationUpdates boolean

Pauses location updates when app is paused.

Platform: iOS Provider: all

(optional)
saveBatteryOnBackground boolean

Switch to less accurate significant changes and region monitory when in background.

Platform: iOS Provider: all

(optional)
url string

Server url where to send HTTP POST with recorded locations

Platform: all Provider: all

(optional)
syncUrl string

Server url where to send fail to post locations

Platform: all Provider: all

(optional)
syncThreshold string

Specifies how many previously failed locations will be sent to server at once.

Platform: all Provider: all

(optional)
httpHeaders any

Optional HTTP headers sent along in HTTP request.

Platform: all Provider: all

(optional)
maxLocations number

Limit maximum number of locations stored into db.

Platform: all Provider: all

(optional)
postTemplate any

Customization post template.

Platform: all Provider: all

(optional)

API

Native

General