Created on 19 October 2022
icon_unfollowing
Login to follow
gps-tracking

GPS Tracking

Stable version 1.0.1 (Compatible with OutSystems 11)
Uploaded on 19 October 2022 by 
gps-tracking

GPS Tracking

Documentation
1.0.1

Usage

First, configure the plugin with the settings you require.

BackgroundGeolocation.configure({
    locationProvider: BackgroundGeolocation.ACTIVITY_PROVIDER,
    desiredAccuracy: BackgroundGeolocation.HIGH_ACCURACY,
    stationaryRadius: 50,
    distanceFilter: 50,
    notificationTitle: 'Background tracking',
    notificationText: 'enabled',
    debug: true,
    interval: 10000,
    fastestInterval: 5000,
    activitiesInterval: 10000,
    url: 'http://192.168.81.15:3000/location',
    httpHeaders: {
      'X-FOO': 'bar'
    },
    // customize post properties
    postTemplate: {
      lat: '@latitude',
      lon: '@longitude',
      foo: 'bar' // you can also add your own properties
    }
  });

Then call start() to start location tracking.

API

Note that all methods now return a Promise in case the success and fail callbacks are not provided, allowing the usage of async/await.

We also recommend using the typescript definitions provided in this repo which have better chance of being up-to-date.


configure(options, success, fail)

Configure options:

ParameterTypePlatformDescriptionProvider*Default
locationProviderNumberallSet location provider @see PROVIDERSN/ADISTANCE_FILTER_PROVIDER
desiredAccuracyNumberallDesired accuracy in meters. Possible values [HIGH_ACCURACY, MEDIUM_ACCURACY, LOW_ACCURACY, PASSIVE_ACCURACY]. Accuracy has direct effect on power drain. Lower accuracy = lower power drain.allMEDIUM_ACCURACY
stationaryRadiusNumberallStationary radius in meters. When stopped, the minimum distance the device must move beyond the stationary location for aggressive background-tracking to engage.DIS50
debugBooleanallWhen enabled, the plugin will emit sounds for life-cycle events of background-geolocation! See debugging sounds table.allfalse
distanceFilterNumberallThe minimum distance (measured in meters) a device must move horizontally before an update event is generated. @see Apple docs.DIS,RAW500
stopOnTerminateBooleanallEnable this in order to force a stop() when the application terminated (e.g. on iOS, double-tap home button, swipe away the app).alltrue
startOnBootBooleanAndroidStart background service on device boot.allfalse
intervalNumberAndroidThe minimum time interval between location updates in milliseconds. @see Android docs for more information.all60000
fastestIntervalNumberAndroidFastest rate in milliseconds at which your app can handle location updates. @see Android docs.ACT120000
activitiesIntervalNumberAndroidRate in milliseconds at which activity recognition occurs. Larger values will result in fewer activity detections while improving battery life.ACT10000
stopOnStillActivityBooleanAndroid@deprecated stop location updates, when the STILL activity is detectedACTtrue
notificationsEnabledBooleanAndroidEnable/disable local notifications when tracking and syncing locationsalltrue
startForegroundBooleanAndroidAllow location sync service to run in foreground state. Foreground state also requires a notification to be presented to the user.allfalse
notificationTitleString optionalAndroidCustom notification title in the drawer. (goes with startForeground)all“Background tracking”
notificationTextString optionalAndroidCustom notification text in the drawer. (goes with startForeground)all“ENABLED”
notificationIconColorString optionalAndroidThe accent color to use for notification. Eg. #4CAF50. (goes with startForeground)all 
notificationIconLargeString optionalAndroidThe filename of a custom notification icon. @see Android quirks. (goes with startForeground)all 
notificationIconSmallString optionalAndroidThe filename of a custom notification icon. @see Android quirks. (goes with startForeground)all 
activityTypeStringiOS[AutomotiveNavigation, OtherNavigation, Fitness, Other] Presumably, this affects iOS GPS algorithm. @see Apple docs for more informationall“OtherNavigation”
pauseLocationUpdatesBooleaniOSPauses location updates when app is paused. *@see Apple docsallfalse
saveBatteryOnBackgroundBooleaniOSSwitch to less accurate significant changes and region monitory when in backgroundallfalse
urlStringallServer url where to send HTTP POST with recorded locations @see HTTP locations postingall 
syncUrlStringallServer url where to send fail to post locations @see HTTP locations postingall 
syncThresholdNumberallSpecifies how many previously failed locations will be sent to server at onceall100
httpHeadersObjectallOptional HTTP headers sent along in HTTP requestall 
maxLocationsNumberallLimit maximum number of locations stored into dball10000
postTemplateObject\|ArrayallCustomization post template @see Custom post templateall 

* DIS = DISTANCE_FILTER_PROVIDER ACT = ACTIVITY_PROVIDER RAW = RAW_PROVIDER

Partial reconfiguration is possible by later providing a subset of the configuration options:

BackgroundGeolocation.configure({
  debug: true
});

In this case new configuration options will be merged with stored configuration options and changes will be applied immediately.

Important: Because configuration options are applied partially, it’s not possible to reset option to default value just by omitting it’s key name and calling configure method. To reset configuration option to the default value, it’s key must be set to null!

// Example: reset postTemplate to default
BackgroundGeolocation.configure({
  postTemplate: null
});


getConfig(success, fail)

Platform: iOS, Android

Get current configuration. Method will return all configuration options and their values in success callback. Because configure method can be called with subset of the configuration options only, getConfig method can be used to check the actual applied configuration.

BackgroundGeolocation.getConfig(function(config) {
  console.log(config);
});


start()

Platform: iOS, Android

Start background geolocation.


stop()

Platform: iOS, Android

Stop background geolocation.


getCurrentLocation(success, fail, options)

Platform: iOS, Android

One time location check to get current location of the device.

Option parameterTypeDescription
timeoutNumberMaximum time in milliseconds device will wait for location
maximumAgeNumberMaximum age in milliseconds of a possible cached location that is acceptable to return
enableHighAccuracyBooleanif true and if the device is able to provide a more accurate position, it will do so


Success callback parameterTypeDescription
locationObjectlocation object (@see Location event)


Error callback parameterTypeDescription
codeNumberReason of an error occurring when using the geolocating device
messageStringMessage describing the details of the error

Error codes:

ValueAssociated constantDescription
1PERMISSION_DENIEDRequest failed due missing permissions
2LOCATION_UNAVAILABLEInternal source of location returned an internal error
3TIMEOUTTimeout defined by `option.timeout was exceeded


isLocationEnabled(success, fail)

Deprecated: This method is deprecated and will be removed in next major version. Use checkStatus as replacement.

Platform: iOS, Android

One time check for status of location services. In case of error, fail callback will be executed.

Success callback parameterTypeDescription
enabledBooleantrue/false (true when location services are enabled)


checkStatus(success, fail)

Check status of the service

Success callback parameterTypeDescription
isRunningBooleantrue/false (true if service is running)
locationServicesEnabledBooleantrue/false (true if location services are enabled)
authorizationNumberauthorization status

Authorization statuses:

  • NOT_AUTHORIZED
  • AUTHORIZED - authorization to run in background and foreground
  • AUTHORIZED_FOREGROUND iOS only authorization to run in foreground only

Note: In the Android concept of authorization, these represent application permissions.


showAppSettings()

Platform: Android >= 6, iOS >= 8.0

Show app settings to allow change of app location permissions.


showLocationSettings()

Platform: Android

Show system settings to allow configuration of current location sources.


getLocations(success, fail)

Platform: iOS, Android

Method will return all stored locations. This method is useful for initial rendering of user location on a map just after application launch.

Success callback parameterTypeDescription
locationsArraycollection of stored locations
BackgroundGeolocation.getLocations(
  function (locations) {
    console.log(locations);
  }
);


getValidLocations(success, fail)

Platform: iOS, Android

Method will return locations which have not yet been posted to server.

Success callback parameterTypeDescription
locationsArraycollection of stored locations


getValidLocationsAndDelete(success, fail)

Platform: iOS, Android

Method will return locations which have not yet been posted to server and delete to avoid getting them again.

Success callback parameterTypeDescription
locationsArraycollection of stored locations


deleteLocation(locationId, success, fail)

Platform: iOS, Android

Delete location with locationId.


deleteAllLocations(success, fail)

Note: You don’t need to delete all locations. The plugin manages the number of stored locations automatically and the total count never exceeds the number as defined by option.maxLocations.

Platform: iOS, Android

Delete all stored locations.

Note: Locations are not actually deleted from database to avoid gaps in locationId numbering. Instead locations are marked as deleted. Locations marked as deleted will not appear in output of BackgroundGeolocation.getValidLocations.


switchMode(modeId, success, fail)

Platform: iOS

Normally the plugin will handle switching between BACKGROUND and FOREGROUND mode itself. Calling switchMode you can override plugin behavior and force it to switch into other mode.

In FOREGROUND mode the 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.

// switch to FOREGROUND mode
BackgroundGeolocation.switchMode(BackgroundGeolocation.FOREGROUND_MODE);

// switch to BACKGROUND mode
BackgroundGeolocation.switchMode(BackgroundGeolocation.BACKGROUND_MODE);


forceSync()

Platform: Android, iOS

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


getLogEntries(limit, fromId, minLevel, success, fail)

Platform: Android, iOS

Return all logged events. Useful for plugin debugging.

ParameterTypeDescription
limitNumberlimits number of returned entries
fromIdNumberreturn entries after fromId. Useful if you plan to implement infinite log scrolling*
minLevelStringreturn log entries above level. Available levels: [“TRACE”, “DEBUG”, “INFO”, “WARN”, “ERROR]
successFunctioncallback function which will be called with log entries

*Example of infinite log scrolling

Format of log entry:

ParameterTypeDescription
idNumberid of log entry as stored in db
timestampNumbertimestamp in milliseconds since beginning of UNIX epoch
levelStringlog level
messageStringlog message
stackTraceStringrecorded stacktrace (Android only, on iOS part of message)


removeAllListeners(event)

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


Events

NameCallback paramPlatformProvider*Description
locationLocationallallon location update
stationaryLocationallDIS,ACTon device entered stationary mode
activityActivityAndroidACTon activity detection
error{ code, message }allallon plugin error
authorizationstatusallallon user toggle location service
start allallgeolocation has been started
stop allallgeolocation has been stopped
foreground Androidallapp entered foreground state (visible)
background Androidallapp entered background state
abort_requested allallserver responded with “285 Updates Not Required”
http_authorization allallserver responded with “401 Unauthorized”


Location event

Location parameterTypeDescription
idNumberID of location as stored in DB (or null)
providerStringgps, network, passive or fused
locationProviderNumberlocation provider
timeNumberUTC time of this fix, in milliseconds since January 1, 1970.
latitudeNumberLatitude, in degrees.
longitudeNumberLongitude, in degrees.
accuracyNumberEstimated accuracy of this location, in meters.
speedNumberSpeed if it is available, in meters/second over ground.
altitudeNumberAltitude if available, in meters above the WGS 84 reference ellipsoid.
bearingNumberBearing, in degrees.
isFromMockProviderBoolean(android only) True if location was recorded by mock provider
mockLocationsEnabledBoolean(android only) True if device has mock locations enabled

Locations parameters isFromMockProvider and mockLocationsEnabled are not posted to url or syncUrl by default. Both can be requested via option postTemplate.

Note: Do not use location id as unique key in your database as ids will be reused when option.maxLocations is reached.


Android background service issues

There are repeatedly reported issues with some android devices not working in the background. Check if your device model is on dontkillmyapp list before you report a new issue. For more information check out dontkillmyapp.com.

Another confusing fact about Android services is the concept of foreground services. Foreground service in the context of Android OS is a different thing than background geolocation service of this plugin (they’re related thought). The plugin’s background geolocation service actually becomes foreground service when app is in the background. Confusing, right? :D

If service wants to continue to run in the background, it must “promote” itself to foreground service. Foreground services must have visible notifications, which is the reason why you can’t disable drawer notifications.

The notification can only be disabled, when the app is running in the foreground, by setting the config option startForeground: false (this is the default option), but will always be visible in the background (if the service was started).

Recommended reading: https://developer.android.com/about/versions/oreo/background


1.0.0

Usage

First, configure the plugin with the settings you require.

BackgroundGeolocation.configure({
    locationProvider: BackgroundGeolocation.ACTIVITY_PROVIDER,
    desiredAccuracy: BackgroundGeolocation.HIGH_ACCURACY,
    stationaryRadius: 50,
    distanceFilter: 50,
    notificationTitle: 'Background tracking',
    notificationText: 'enabled',
    debug: true,
    interval: 10000,
    fastestInterval: 5000,
    activitiesInterval: 10000,
    url: 'http://192.168.81.15:3000/location',
    httpHeaders: {
      'X-FOO': 'bar'
    },
    // customize post properties
    postTemplate: {
      lat: '@latitude',
      lon: '@longitude',
      foo: 'bar' // you can also add your own properties
    }
  });

Then call start() to start location tracking.

API

Note that all methods now return a Promise in case the success and fail callbacks are not provided, allowing the usage of async/await.

We also recommend using the typescript definitions provided in this repo which have better chance of being up-to-date.


configure(options, success, fail)

Configure options:

ParameterTypePlatformDescriptionProvider*Default
locationProviderNumberallSet location provider @see PROVIDERSN/ADISTANCE_FILTER_PROVIDER
desiredAccuracyNumberallDesired accuracy in meters. Possible values [HIGH_ACCURACY, MEDIUM_ACCURACY, LOW_ACCURACY, PASSIVE_ACCURACY]. Accuracy has direct effect on power drain. Lower accuracy = lower power drain.allMEDIUM_ACCURACY
stationaryRadiusNumberallStationary radius in meters. When stopped, the minimum distance the device must move beyond the stationary location for aggressive background-tracking to engage.DIS50
debugBooleanallWhen enabled, the plugin will emit sounds for life-cycle events of background-geolocation! See debugging sounds table.allfalse
distanceFilterNumberallThe minimum distance (measured in meters) a device must move horizontally before an update event is generated. @see Apple docs.DIS,RAW500
stopOnTerminateBooleanallEnable this in order to force a stop() when the application terminated (e.g. on iOS, double-tap home button, swipe away the app).alltrue
startOnBootBooleanAndroidStart background service on device boot.allfalse
intervalNumberAndroidThe minimum time interval between location updates in milliseconds. @see Android docs for more information.all60000
fastestIntervalNumberAndroidFastest rate in milliseconds at which your app can handle location updates. @see Android docs.ACT120000
activitiesIntervalNumberAndroidRate in milliseconds at which activity recognition occurs. Larger values will result in fewer activity detections while improving battery life.ACT10000
stopOnStillActivityBooleanAndroid@deprecated stop location updates, when the STILL activity is detectedACTtrue
notificationsEnabledBooleanAndroidEnable/disable local notifications when tracking and syncing locationsalltrue
startForegroundBooleanAndroidAllow location sync service to run in foreground state. Foreground state also requires a notification to be presented to the user.allfalse
notificationTitleString optionalAndroidCustom notification title in the drawer. (goes with startForeground)all“Background tracking”
notificationTextString optionalAndroidCustom notification text in the drawer. (goes with startForeground)all“ENABLED”
notificationIconColorString optionalAndroidThe accent color to use for notification. Eg. #4CAF50. (goes with startForeground)all 
notificationIconLargeString optionalAndroidThe filename of a custom notification icon. @see Android quirks. (goes with startForeground)all 
notificationIconSmallString optionalAndroidThe filename of a custom notification icon. @see Android quirks. (goes with startForeground)all 
activityTypeStringiOS[AutomotiveNavigation, OtherNavigation, Fitness, Other] Presumably, this affects iOS GPS algorithm. @see Apple docs for more informationall“OtherNavigation”
pauseLocationUpdatesBooleaniOSPauses location updates when app is paused. *@see Apple docsallfalse
saveBatteryOnBackgroundBooleaniOSSwitch to less accurate significant changes and region monitory when in backgroundallfalse
urlStringallServer url where to send HTTP POST with recorded locations @see HTTP locations postingall 
syncUrlStringallServer url where to send fail to post locations @see HTTP locations postingall 
syncThresholdNumberallSpecifies how many previously failed locations will be sent to server at onceall100
httpHeadersObjectallOptional HTTP headers sent along in HTTP requestall 
maxLocationsNumberallLimit maximum number of locations stored into dball10000
postTemplateObject\|ArrayallCustomization post template @see Custom post templateall 

* DIS = DISTANCE_FILTER_PROVIDER ACT = ACTIVITY_PROVIDER RAW = RAW_PROVIDER

Partial reconfiguration is possible by later providing a subset of the configuration options:

BackgroundGeolocation.configure({
  debug: true
});

In this case new configuration options will be merged with stored configuration options and changes will be applied immediately.

Important: Because configuration options are applied partially, it’s not possible to reset option to default value just by omitting it’s key name and calling configure method. To reset configuration option to the default value, it’s key must be set to null!

// Example: reset postTemplate to default
BackgroundGeolocation.configure({
  postTemplate: null
});


getConfig(success, fail)

Platform: iOS, Android

Get current configuration. Method will return all configuration options and their values in success callback. Because configure method can be called with subset of the configuration options only, getConfig method can be used to check the actual applied configuration.

BackgroundGeolocation.getConfig(function(config) {
  console.log(config);
});


start()

Platform: iOS, Android

Start background geolocation.


stop()

Platform: iOS, Android

Stop background geolocation.


getCurrentLocation(success, fail, options)

Platform: iOS, Android

One time location check to get current location of the device.

Option parameterTypeDescription
timeoutNumberMaximum time in milliseconds device will wait for location
maximumAgeNumberMaximum age in milliseconds of a possible cached location that is acceptable to return
enableHighAccuracyBooleanif true and if the device is able to provide a more accurate position, it will do so


Success callback parameterTypeDescription
locationObjectlocation object (@see Location event)


Error callback parameterTypeDescription
codeNumberReason of an error occurring when using the geolocating device
messageStringMessage describing the details of the error

Error codes:

ValueAssociated constantDescription
1PERMISSION_DENIEDRequest failed due missing permissions
2LOCATION_UNAVAILABLEInternal source of location returned an internal error
3TIMEOUTTimeout defined by `option.timeout was exceeded


isLocationEnabled(success, fail)

Deprecated: This method is deprecated and will be removed in next major version. Use checkStatus as replacement.

Platform: iOS, Android

One time check for status of location services. In case of error, fail callback will be executed.

Success callback parameterTypeDescription
enabledBooleantrue/false (true when location services are enabled)


checkStatus(success, fail)

Check status of the service

Success callback parameterTypeDescription
isRunningBooleantrue/false (true if service is running)
locationServicesEnabledBooleantrue/false (true if location services are enabled)
authorizationNumberauthorization status

Authorization statuses:

  • NOT_AUTHORIZED
  • AUTHORIZED - authorization to run in background and foreground
  • AUTHORIZED_FOREGROUND iOS only authorization to run in foreground only

Note: In the Android concept of authorization, these represent application permissions.


showAppSettings()

Platform: Android >= 6, iOS >= 8.0

Show app settings to allow change of app location permissions.


showLocationSettings()

Platform: Android

Show system settings to allow configuration of current location sources.


getLocations(success, fail)

Platform: iOS, Android

Method will return all stored locations. This method is useful for initial rendering of user location on a map just after application launch.

Success callback parameterTypeDescription
locationsArraycollection of stored locations
BackgroundGeolocation.getLocations(
  function (locations) {
    console.log(locations);
  }
);


getValidLocations(success, fail)

Platform: iOS, Android

Method will return locations which have not yet been posted to server.

Success callback parameterTypeDescription
locationsArraycollection of stored locations


getValidLocationsAndDelete(success, fail)

Platform: iOS, Android

Method will return locations which have not yet been posted to server and delete to avoid getting them again.

Success callback parameterTypeDescription
locationsArraycollection of stored locations


deleteLocation(locationId, success, fail)

Platform: iOS, Android

Delete location with locationId.


deleteAllLocations(success, fail)

Note: You don’t need to delete all locations. The plugin manages the number of stored locations automatically and the total count never exceeds the number as defined by option.maxLocations.

Platform: iOS, Android

Delete all stored locations.

Note: Locations are not actually deleted from database to avoid gaps in locationId numbering. Instead locations are marked as deleted. Locations marked as deleted will not appear in output of BackgroundGeolocation.getValidLocations.


switchMode(modeId, success, fail)

Platform: iOS

Normally the plugin will handle switching between BACKGROUND and FOREGROUND mode itself. Calling switchMode you can override plugin behavior and force it to switch into other mode.

In FOREGROUND mode the 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.

// switch to FOREGROUND mode
BackgroundGeolocation.switchMode(BackgroundGeolocation.FOREGROUND_MODE);

// switch to BACKGROUND mode
BackgroundGeolocation.switchMode(BackgroundGeolocation.BACKGROUND_MODE);


forceSync()

Platform: Android, iOS

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


getLogEntries(limit, fromId, minLevel, success, fail)

Platform: Android, iOS

Return all logged events. Useful for plugin debugging.

ParameterTypeDescription
limitNumberlimits number of returned entries
fromIdNumberreturn entries after fromId. Useful if you plan to implement infinite log scrolling*
minLevelStringreturn log entries above level. Available levels: [“TRACE”, “DEBUG”, “INFO”, “WARN”, “ERROR]
successFunctioncallback function which will be called with log entries

*Example of infinite log scrolling

Format of log entry:

ParameterTypeDescription
idNumberid of log entry as stored in db
timestampNumbertimestamp in milliseconds since beginning of UNIX epoch
levelStringlog level
messageStringlog message
stackTraceStringrecorded stacktrace (Android only, on iOS part of message)


removeAllListeners(event)

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


Events

NameCallback paramPlatformProvider*Description
locationLocationallallon location update
stationaryLocationallDIS,ACTon device entered stationary mode
activityActivityAndroidACTon activity detection
error{ code, message }allallon plugin error
authorizationstatusallallon user toggle location service
start allallgeolocation has been started
stop allallgeolocation has been stopped
foreground Androidallapp entered foreground state (visible)
background Androidallapp entered background state
abort_requested allallserver responded with “285 Updates Not Required”
http_authorization allallserver responded with “401 Unauthorized”


Location event

Location parameterTypeDescription
idNumberID of location as stored in DB (or null)
providerStringgps, network, passive or fused
locationProviderNumberlocation provider
timeNumberUTC time of this fix, in milliseconds since January 1, 1970.
latitudeNumberLatitude, in degrees.
longitudeNumberLongitude, in degrees.
accuracyNumberEstimated accuracy of this location, in meters.
speedNumberSpeed if it is available, in meters/second over ground.
altitudeNumberAltitude if available, in meters above the WGS 84 reference ellipsoid.
bearingNumberBearing, in degrees.
isFromMockProviderBoolean(android only) True if location was recorded by mock provider
mockLocationsEnabledBoolean(android only) True if device has mock locations enabled

Locations parameters isFromMockProvider and mockLocationsEnabled are not posted to url or syncUrl by default. Both can be requested via option postTemplate.

Note: Do not use location id as unique key in your database as ids will be reused when option.maxLocations is reached.


Android background service issues

There are repeatedly reported issues with some android devices not working in the background. Check if your device model is on dontkillmyapp list before you report a new issue. For more information check out dontkillmyapp.com.

Another confusing fact about Android services is the concept of foreground services. Foreground service in the context of Android OS is a different thing than background geolocation service of this plugin (they’re related thought). The plugin’s background geolocation service actually becomes foreground service when app is in the background. Confusing, right? :D

If service wants to continue to run in the background, it must “promote” itself to foreground service. Foreground services must have visible notifications, which is the reason why you can’t disable drawer notifications.

The notification can only be disabled, when the app is running in the foreground, by setting the config option startForeground: false (this is the default option), but will always be visible in the background (if the service was started).

Recommended reading: https://developer.android.com/about/versions/oreo/background


Support options
This asset is not supported by OutSystems. You may use the discussion forums to leave suggestions or obtain best-effort support from the community, including from  who created this asset.
Dependencies
See all 1 dependencies