Options
All
  • Public
  • Public/Protected
  • All
Menu

Primary API of the SDK.

break

📚 Help

⚡ī¸ Events

BackgroundGeolocation is event-based. Interacting with the SDK is largely through implementing listeners on the following events:

Method Description
onLocation Fired with each recorded Location
onMotionChange Fired when the plugin changes state between moving / stationary
onHttp Fired with each HTTP response from your server. (see Config.url).
onActivityChange Fired with each change in device motion-activity.
onProviderChange Fired after changes to device location-services configuration.
onHeartbeat Periodic timed events. See heartbeatInterval. iOS requires preventSuspend.
onGeofence Fired with each Geofence transition event (ENTER, EXIT, DWELL).
onGeofencesChange Fired when the list of actively-monitored geofences changed. See geofenceProximityRadius.
onSchedule Fired for schedule events.
onConnectivityChange Fired when network-connectivity changes (connected / disconnected).
onPowerSaveChange Fired when state of operating-system's "power-saving" feature is enabled / disabled.
onEnabledChange Fired when the plugin is enabled / disabled via its start / stop methods.
onAuthorization Fired when a response from Authorization.refreshUrl is received.
onNotificationAction Android only: Fired when a button is clicked on a custom Notification.layout of a foreground-service notification.

🔧 Config API

BackgroundGeolocation is highly configurable. See the Config API for more information.

There are three main steps to using BackgroundGeolocation

  1. Wire up event-listeners.
  2. ready the SDK.
  3. start tracking.
example

////
// 1.  Wire up event-listeners
//

// This handler fires whenever bgGeo receives a location update.
BackgroundGeolocation.onLocation(location => {
  console.log("[location] ", location);
}, error => {
  console.log("[location] ERROR: ", error);
});

// This handler fires when movement states changes (stationary->moving; moving->stationary)
BackgroundGeolocation.onMotionChange(location => {
  console.log("[motionchange] ", location);
});

// This handler fires on HTTP responses
BackgroundGeolocation.onHttp(response => {
  console.log("[http] ", response);
});

// This event fires when a change in motion activity is detected
BackgroundGeolocation.onActivityChange(activityEvent => {
  console.log("[activitychange] ", activityEvent);
});

// This event fires when the user toggles location-services authorization
BackgroundGeolocation.onProviderChange(providerEvent => {
  console.log("[providerchange] ", providerEvent);
});

////
// 2.  Execute #ready method (required)
//
BackgroundGeolocation.ready({
  // Geolocation Config
  desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
  distanceFilter: 10,
  // Activity Recognition
  stopTimeout: 1,
  // Application config
  debug: true,              // <-- enable this hear debug sounds.
  logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
  stopOnTerminate: false,   // <-- Allow the background-service to continue tracking when app terminated.
  startOnBoot: true,        // <-- Auto start tracking when device is powered-up.
  // HTTP / SQLite config
  url: "http://yourserver.com/locations",
  batchSync: false,       // <-- Set true to sync locations to server in a single HTTP request.
  autoSync: true,         // <-- Set true to sync each location to server as it arrives.
  headers: {              // <-- Optional HTTP headers
    "X-FOO": "bar"
  },
  params: {               // <-- Optional HTTP params
    "auth_token": "maybe_your_server_authenticates_via_token_YES?"
  }
}, (state) => {
  console.log("- BackgroundGeolocation is configured and ready: ", state.enabled);

  if (!state.enabled) {
    ////
    // 3. Start tracking!
    //
    BackgroundGeolocation.start(function() {
      console.log("- Start success");
    });
  }
});

example
BackgroundGeolocation.ready({
  distanceFilter: 10,
  stopOnTerminate: false,
  logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
  debug: true
}, (state) => {
  console.log("- BackgroundGeolocation is ready: ", state);
});

⚠ī¸ Warning:

Do not execute any API method which will require accessing location-services until the callback to ready executes (eg: getCurrentPosition, watchPosition, start).

Promise API

The BackgroundGeolocation Javascript API supports Promises for nearly every method (the exceptions are watchPosition and adding event-listeners via #onEventName methods.)

example
// Traditional API still works:
BackgroundGeolocation.ready({desiredAccuracy: 0, distanceFilter: 50}).then(state => {
  console.log("- BackgroundGeolocation is ready: ", state);
}).catch(error => {
  console.log("- BackgroundGeolocation error: ", error);
});

Hierarchy

  • BackgroundGeolocation

Index

Constructors

Events

Properties

Methods

Constructors

constructor

Events

Static onActivityChange

  • Subscribe to changes in motion activity.

    Your callback will be executed each time the activity-recognition system receives an event (still, on_foot, in_vehicle, on_bicycle, running).

    Android

    Android MotionActivityEvent.confidence always reports 100%.

    example
    const subscription = BackgroundGeolocation.onActivityChange((event) => {
      console.log("[onActivityChange] ", event);
    });
    

    Parameters

    Returns Subscription

Static onConnectivityChange

  • Subscribe to changes in network connectivity.

    Fired when the state of the device's network-connectivity changes (enabled -> disabled and vice-versa). By default, the plugin will automatically fire a connectivitychange event with the current state network-connectivity whenever the start method is executed.

    ℹī¸ The SDK subscribes internally to connectivitychange events — if you've configured the SDK's HTTP Service (See HTTP Guide) and your app has queued locations, the SDK will automatically initiate uploading to your configured Config.url when network connectivity is detected.

    example
    const subscription = BackgroundGeolocation.onConnectivityChange((event) => {
      console.log("[onConnectivityChange] ", event);
    });
    

    Parameters

    Returns Subscription

Static onEnabledChange

  • onEnabledChange(callback: (enabled: boolean) => void): Subscription
  • Subscribe to changes in plugin State.enabled.

    Fired when the SDK's State.enabled changes. For example, executing start and stop will cause the onEnabledChnage event to fire. This event is primarily designed for use with the configuration option stopAfterElapsedMinutes, which automatically executes the SDK's stop method.

    example
    const subscription = BackgroundGeolocation.onEnabledChange(isEnabled => {
      console.log("[onEnabledChanged] isEnabled? ", isEnabled);
    });
    

    Parameters

    • callback: (enabled: boolean) => void
        • (enabled: boolean): void
        • Parameters

          • enabled: boolean

          Returns void

    Returns Subscription

Static onGeofence

Static onGeofencesChange

  • Subscribe to changes in actively monitored geofences.

    Fired when the list of monitored-geofences changed. The BackgroundGeolocation SDK contains powerful geofencing features that allow you to monitor any number of circular geofences you wish (thousands even), in spite of limits imposed by the native platform APIs (20 for iOS; 100 for Android).

    The plugin achieves this by storing your geofences in its database, using a geospatial query to determine those geofences in proximity (@see geofenceProximityRadius), activating only those geofences closest to the device's current location (according to limit imposed by the corresponding platform).

    When the device is determined to be moving, the plugin periodically queries for geofences in proximity (eg. every minute) using the latest recorded location. This geospatial query is very fast, even with tens-of-thousands geofences in the database.

    It's when this list of monitored geofences changes, that the plugin will fire the onGeofencesChange event.

    example
    const subscription = BackgroundGeolocation.onGeofencesChange((event) => {
      let on = event.on;     //<-- new geofences activated.
      let off = event.off; //<-- geofences that were just de-activated.
    
      // Create map circles
      on.forEach((geofence) => {
        createGeofenceMarker(geofence)
      });
    
      // Remove map circles
      off.forEach((identifier) => {
        removeGeofenceMarker(identifier);
      }
    });
    

    ℹī¸ See also:

    Parameters

    Returns Subscription

Static onHeartbeat

  • Subscribe to periodic heartbeat events.

    Your callback will be executed for each heartbeatInterval while the device is in stationary state (iOS requires preventSuspend: true as well).

    example
    BackgroundGeolocation.ready({
      heartbeatInterval: 60,
      preventSuspend: true // <-- Required for iOS
    });
    
    const subscription = BackgroundGeolocation.onHeartbeat((event) => {
      console.log("[onHeartbeat] ", event);
    
      // You could request a new location if you wish.
      BackgroundGeolocation.getCurrentPosition({
        samples: 1,
        persist: true
      }).then((location) => {
        console.log("[getCurrentPosition] ", location);
      });
    })
    

    ⚠ī¸ Note:

    • The Location provided by the HeartbeatEvent is only the last-known location. The heartbeat event does not actively engage location-services. If you wish to get the current location in your callback, use getCurrentPosition.

    Parameters

    Returns Subscription

Static onHttp

  • Subscribe to HTTP responses from your server Config.url.

    example
    const subscription = BackgroundGeolocation.onHttp((response) => {
      let status = response.status;
      let success = response.success;
      let responseText = response.responseText;
      console.log("[onHttp] ", response);
    });
    

    ℹī¸ See also:

    Parameters

    Returns Subscription

Static onLocation

  • Subscribe to location events.

    Every location recorded by the SDK is provided to your callback, including those from onMotionChange, getCurrentPosition and watchPosition.

    example
    const subscription = BackgroundGeolocation.onLocation((location) => {
      console.log("[onLocation] success: ", location);
    }, (error) => {
      console.log("[onLocation] ERROR: ", error);
    });
    

    Error Codes

    If the native location API fails to return a location, the failure callback will be provided a LocationError.

    ⚠ī¸ Note Location.sample:

    When performing a onMotionChange or getCurrentPosition, the plugin requests multiple location samples in order to record the most accurate location possible. These samples are not persisted to the database but they will be provided to your callback, for your convenience, since it can take some seconds for the best possible location to arrive.

    For example, you might use these samples to progressively update the user's position on a map. You can detect these samples in your callback via location.sample == true. If you're manually POSTing location to your server, you should ignore these locations.

    Parameters

    Returns Subscription

Static onMotionChange

  • Subscribe to motionchange events.

    Your callback will be executed each time the device has changed-state between MOVING or STATIONARY.

    example
    const subscription = BackgroundGeolocation.onMotionChange((event) => {
      if (event.isMoving) {
         console.log("[onMotionChange] Device has just started MOVING ", event.location);
      } else {
         console.log("[onMotionChange] Device has just STOPPED:  ", event.location);
      }
    });
    

    ⚠ī¸ Warning: autoSyncThreshold

    If you've configured Config.autoSyncThreshold, it will be ignored during a onMotionChange event — all queued locations will be uploaded, since:

    • If an onMotionChange event fires into the moving state, the device may have been sitting dormant for a long period of time. The plugin is eager to upload this state-change to the server as soon as possible.
    • If an onMotionChange event fires into the stationary state, the device may be about to lie dormant for a long period of time. The plugin is eager to upload all queued locations to the server before going dormant.

    ℹī¸ See also:

    Parameters

    Returns Subscription

Static onPowerSaveChange

  • onPowerSaveChange(callback: (enabled: boolean) => void): Subscription
  • Subscribe to state changes in OS power-saving system.

    Fired when the state of the operating-system's "Power Saving" mode changes. Your callback will be provided with a bool showing whether "Power Saving" is enabled or disabled. Power Saving mode can throttle certain services in the background, such as HTTP requests or GPS.

    break

    ℹī¸ You can manually request the current-state of "Power Saving" mode with the method isPowerSaveMode.

    iOS

    iOS Power Saving mode can be engaged manually by the user in Settings -> Battery or from an automatic OS dialog.

    Android

    Android Power Saving mode can be engaged manually by the user in Settings -> Battery -> Battery Saver or automatically with a user-specified "threshold" (eg: 15%).

    example
    const subscription = BackgroundGeolocation.onPowerSaveChange((isPowerSaveMode) => {
      console.log("[onPowerSaveChange: ", isPowerSaveMode);
    });
    

    Parameters

    • callback: (enabled: boolean) => void
        • (enabled: boolean): void
        • Parameters

          • enabled: boolean

          Returns void

    Returns Subscription

Static onProviderChange

  • Subscribe to changes in device's location-services configuration / authorization.

    Your callback fill be executed whenever a change in the state of the device's Location Services has been detected. eg: "GPS ON", "WiFi only".

    example
    const subscription = BackgroundGeolocation.onProviderChange((event) => {
      console.log("[onProviderChange: ", event);
    
      switch(event.status) {
        case BackgroundGeolocation.AUTHORIZATION_STATUS_DENIED:
          // Android & iOS
          console.log("- Location authorization denied");
          break;
        case BackgroundGeolocation.AUTHORIZATION_STATUS_ALWAYS:
          // Android & iOS
          console.log("- Location always granted");
          break;
        case BackgroundGeolocation.AUTHORIZATION_STATUS_WHEN_IN_USE:
          // iOS only
          console.log("- Location WhenInUse granted");
          break;
      }
    });
    

    ℹī¸ See also:

    • You can explicitly request the current state of location-services using getProviderState.

    ⚠ī¸ Note:

    • The plugin always force-fires an onProviderChange event whenever the app is launched (right after the ready method is executed), regardless of current state, so you can learn the the current state of location-services with each boot of your application.

    Parameters

    Returns Subscription

Static onSchedule

  • Subscribe to schedule events.

    Your callback will be executed each time a schedule event fires. Your callback will be provided with the current State: state.enabled will reflect the state according to your schedule.

    example
    const subscription = BackgroundGeolocation.onSchedule((state) => {
      if (state.enabled) {
        console.log("[onSchedule] scheduled start tracking");
      } else {
        console.log("[onSchedule] scheduled stop tracking");
      }
    });
    

    Parameters

    • callback: (state: State) => void
        • Parameters

          Returns void

    Returns Subscription

Properties

Static ACCURACY_AUTHORIZATION_FULL

ACCURACY_AUTHORIZATION_FULL: AccuracyAuthorization

Static ACCURACY_AUTHORIZATION_REDUCED

ACCURACY_AUTHORIZATION_REDUCED: AccuracyAuthorization

Static ACTIVITY_TYPE_AUTOMOTIVE_NAVIGATION

ACTIVITY_TYPE_AUTOMOTIVE_NAVIGATION: ActivityType

Static ACTIVITY_TYPE_FITNESS

ACTIVITY_TYPE_FITNESS: ActivityType

Static ACTIVITY_TYPE_OTHER

ACTIVITY_TYPE_OTHER: ActivityType

Static ACTIVITY_TYPE_OTHER_NAVIGATION

ACTIVITY_TYPE_OTHER_NAVIGATION: ActivityType

Static AUTHORIZATION_STATUS_ALWAYS

AUTHORIZATION_STATUS_ALWAYS: AuthorizationStatus

Static AUTHORIZATION_STATUS_DENIED

AUTHORIZATION_STATUS_DENIED: AuthorizationStatus

Static AUTHORIZATION_STATUS_NOT_DETERMINED

AUTHORIZATION_STATUS_NOT_DETERMINED: AuthorizationStatus

Static AUTHORIZATION_STATUS_RESTRICTED

AUTHORIZATION_STATUS_RESTRICTED: AuthorizationStatus

Static AUTHORIZATION_STATUS_WHEN_IN_USE

AUTHORIZATION_STATUS_WHEN_IN_USE: AuthorizationStatus

Static DESIRED_ACCURACY_HIGH

DESIRED_ACCURACY_HIGH: LocationAccuracy

Static DESIRED_ACCURACY_LOW

DESIRED_ACCURACY_LOW: LocationAccuracy

Static DESIRED_ACCURACY_LOWEST

DESIRED_ACCURACY_LOWEST: LocationAccuracy

Static DESIRED_ACCURACY_MEDIUM

DESIRED_ACCURACY_MEDIUM: LocationAccuracy

Static DESIRED_ACCURACY_NAVIGATION

DESIRED_ACCURACY_NAVIGATION: LocationAccuracy

Static DESIRED_ACCURACY_VERY_LOW

DESIRED_ACCURACY_VERY_LOW: LocationAccuracy

Static EVENT_ACTIVITYCHANGE

EVENT_ACTIVITYCHANGE: Event

Static EVENT_AUTHORIZATION

EVENT_AUTHORIZATION: Event

Static EVENT_BOOT

EVENT_BOOT: Event

Static EVENT_CONNECTIVITYCHANGE

EVENT_CONNECTIVITYCHANGE: Event

Static EVENT_ENABLEDCHANGE

EVENT_ENABLEDCHANGE: Event

Static EVENT_GEOFENCE

EVENT_GEOFENCE: Event

Static EVENT_GEOFENCESCHANGE

EVENT_GEOFENCESCHANGE: Event

Static EVENT_HEARTBEAT

EVENT_HEARTBEAT: Event

Static EVENT_HTTP

EVENT_HTTP: Event

Static EVENT_LOCATION

EVENT_LOCATION: Event

Static EVENT_MOTIONCHANGE

EVENT_MOTIONCHANGE: Event

Static EVENT_NOTIFICATIONACTION

EVENT_NOTIFICATIONACTION: Event

Static EVENT_POWERSAVECHANGE

EVENT_POWERSAVECHANGE: Event

Static EVENT_PROVIDERCHANGE

EVENT_PROVIDERCHANGE: Event

Static EVENT_SCHEDULE

EVENT_SCHEDULE: Event

Static EVENT_TERMINATE

EVENT_TERMINATE: Event

Static LOG_LEVEL_DEBUG

LOG_LEVEL_DEBUG: LogLevel

Static LOG_LEVEL_ERROR

LOG_LEVEL_ERROR: LogLevel

Static LOG_LEVEL_INFO

LOG_LEVEL_INFO: LogLevel

Static LOG_LEVEL_OFF

LOG_LEVEL_OFF: LogLevel

Static LOG_LEVEL_VERBOSE

LOG_LEVEL_VERBOSE: LogLevel

Static LOG_LEVEL_WARNING

LOG_LEVEL_WARNING: LogLevel

Static NOTIFICATION_PRIORITY_DEFAULT

NOTIFICATION_PRIORITY_DEFAULT: NotificationPriority

Static NOTIFICATION_PRIORITY_HIGH

NOTIFICATION_PRIORITY_HIGH: NotificationPriority

Static NOTIFICATION_PRIORITY_LOW

NOTIFICATION_PRIORITY_LOW: NotificationPriority

Static NOTIFICATION_PRIORITY_MAX

NOTIFICATION_PRIORITY_MAX: NotificationPriority

Static NOTIFICATION_PRIORITY_MIN

NOTIFICATION_PRIORITY_MIN: NotificationPriority

Static PERSIST_MODE_ALL

PERSIST_MODE_ALL: PersistMode

Static PERSIST_MODE_GEOFENCE

PERSIST_MODE_GEOFENCE: PersistMode

Static PERSIST_MODE_LOCATION

PERSIST_MODE_LOCATION: PersistMode

Static PERSIST_MODE_NONE

PERSIST_MODE_NONE: PersistMode

Static deviceSettings

deviceSettings: DeviceSettings

Provides an API to show Android & vendor-specific Battery / Power Management settings screens that can affect performance of the Background Geolocation SDK on various devices.

The site Don't Kill My App provides a comprehensive list of poor Android vendors which throttle background-services that this plugin relies upon.

This DeviceSettings API is an attempt to provide resources to direct the user to the appropriate vendor-specific settings screen to resolve issues with background operation.

Static logger

logger: Logger

Logger API

Methods

Static addGeofence

  • addGeofence(config: Geofence, success?: Function, failure?: (error: string) => void): Promise<void>
  • Adds a Geofence to be monitored by the native Geofencing API.

    example
    BackgroundGeolocation.addGeofence({
      identifier: "Home",
      radius: 150,
      latitude: 45.51921926,
      longitude: -73.61678581,
      notifyOnEntry: true,
      notifyOnExit: false,
      notifyOnDwell: true,
      loiteringDelay: 30000,  // 30 seconds
      extras: {               // Optional arbitrary meta-data
        zone_id: 1234
      }
    }).then((success) => {
      console.log("[addGeofence] success");
    }).catch((error) => {
      console.log("[addGeofence] FAILURE: ", error);
    });
    

    ℹī¸ Note:

    • If a geofence(s) already exists with the configured Geofence.identifier, the previous one(s) will be deleted before the new one is inserted.
    • When adding multiple, it's about 10 times faster to use addGeofences instead.
    • 📘 Geofencing Guide

    Parameters

    • config: Geofence
    • Optional success: Function
    • Optional failure: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<void>

Static addGeofences

  • addGeofences(geofences: Geofence[], success?: Function, failure?: Function): Promise<void>
  • Adds a list of Geofence to be monitored by the native Geofencing API.

    example
    let geofences = [{
      identifier: "foo",
      radius: 200,
      latitude: 45.51921926,
      longitude: -73.61678581,
      notifyOnEntry: true
    },
      identifier: "bar",
      radius: 200,
      latitude: 45.51921926,
      longitude: -73.61678581,
      notifyOnEntry: true
    }];
    
    BackgroundGeolocation.addGeofences(geofences);
    

    ℹī¸ Note:

    Parameters

    • geofences: Geofence[]
    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static changePace

  • changePace(isMoving: boolean, success?: Function, failure?: (error: string) => void): Promise<void>
  • Manually toggles the SDK's motion state between stationary and moving.

    When provided a value of true, the plugin will engage location-services and begin aggressively tracking the device's location immediately, bypassing stationary monitoring.

    If you were making a "Jogging" application, this would be your [Start Workout] button to immediately begin location-tracking. Send false to turn off location-services and return the plugin to the stationary state.

    example
    BackgroundGeolocation.changePace(true);  // <-- Location-services ON ("moving" state)
    BackgroundGeolocation.changePace(false); // <-- Location-services OFF ("stationary" state)
    

    Parameters

    • isMoving: boolean
    • Optional success: Function
    • Optional failure: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<void>

Static destroyLocation

  • destroyLocation(uuid: String): Promise<void>
  • Destroy a single location by Location.uuid

    example
    await BackgroundGeolocation.destroyLocation(location.uuid);
    

    Parameters

    • uuid: String

    Returns Promise<void>

Static destroyLocations

  • destroyLocations(success?: Function, failure?: Function): Promise<void>
  • Remove all records in SDK's SQLite database.

    example
    let success = await BackgroundGeolocation.destroyLocations();
    

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static destroyLog

  • destroyLog(success?: Function, failure?: Function): Promise<void>
  • deprecated

    Use Logger.destroyLog.

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static destroyTransistorAuthorizationToken

  • destroyTransistorAuthorizationToken(url?: string): Promise<boolean>

Static emailLog

  • emailLog(email: string, success?: Function, failure?: (error: string) => void): Promise<void>
  • deprecated

    Use Logger.emailLog.

    Parameters

    • email: string
    • Optional success: Function
    • Optional failure: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<void>

Static findOrCreateTransistorAuthorizationToken

Static finish

  • finish(taskId: number, success?: Function, failure?: Function): Promise<number>
  • alias

    stopBackgroundTask

    deprecated

    Parameters

    • taskId: number
    • Optional success: Function
    • Optional failure: Function

    Returns Promise<number>

Static geofenceExists

  • geofenceExists(identifier: string, callback?: (exists: boolean) => void): Promise<boolean>
  • Determine if a particular geofence exists in the SDK's database.

    example
    let exists = await BackgroundGeolocation.geofenceExists("HOME");
    console.log("[geofenceExists] ", exists);
    

    ℹī¸ See also:

    Parameters

    • identifier: string
    • Optional callback: (exists: boolean) => void
        • (exists: boolean): void
        • Parameters

          • exists: boolean

          Returns void

    Returns Promise<boolean>

Static getCount

  • getCount(success?: (count: number) => void, failure?: Function): Promise<number>
  • Retrieve the count of all locations current stored in the SDK's SQLite database.

    example
    let count = await BackgroundGeolocation.getCount();
    

    Parameters

    • Optional success: (count: number) => void
        • (count: number): void
        • Parameters

          • count: number

          Returns void

    • Optional failure: Function

    Returns Promise<number>

Static getCurrentPosition

  • Retrieves the current Location.

    This method instructs the native code to fetch exactly one location using maximum power & accuracy. The native code will persist the fetched location to its SQLite database just as any other location in addition to POSTing to your configured Config.url. If an error occurs while fetching the location, catch will be provided with an LocationError.

    break

    Options

    See CurrentPositionRequest.

    Error Codes

    See LocationError.

    example
    let location = await BackgroundGeolocation.getCurrentPosition({
      timeout: 30,          // 30 second timeout to fetch location
      maximumAge: 5000,     // Accept the last-known-location if not older than 5000 ms.
      desiredAccuracy: 10,  // Try to fetch a location with an accuracy of `10` meters.
      samples: 3,           // How many location samples to attempt.
      extras: {             // Custom meta-data.
        "route_id": 123
      }
    });
    

    ⚠ī¸ Note:

    Parameters

    Returns Promise<Location>

Static getDeviceInfo

Static getGeofence

  • getGeofence(identifier: string, success?: (geofence: Geofence) => void, failure?: (error: string) => void): Promise<Geofence>
  • Fetch a single Geofence by identifier from the SDK's database.

    example
    let geofence = await BackgroundGeolocation.getGeofence("HOME");
    console.log("[getGeofence] ", geofence);
    

    ℹī¸ See also:

    Parameters

    • identifier: string
    • Optional success: (geofence: Geofence) => void
    • Optional failure: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<Geofence>

Static getGeofences

  • getGeofences(success?: (geofences: Geofence[]) => void, failure?: (error: string) => void): Promise<Geofence[]>
  • Fetch a list of all Geofence in the SDK's database. If there are no geofences being monitored, you'll receive an empty Array.

    example
    let geofences = await BackgroundGeolocation.getGeofences();
    console.log("[getGeofences: ", geofences);
    

    ℹī¸ See also:

    Parameters

    • Optional success: (geofences: Geofence[]) => void
    • Optional failure: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<Geofence[]>

Static getLocations

  • getLocations(success?: (locations: Object[]) => void, failure?: Function): Promise<Object[]>
  • Retrieve a List of Location currently stored in the SDK's SQLite database.

    example
    let locations = await BackgroundGeolocation.getLocations();
    

    Parameters

    • Optional success: (locations: Object[]) => void
        • (locations: Object[]): void
        • Parameters

          • locations: Object[]

          Returns void

    • Optional failure: Function

    Returns Promise<Object[]>

Static getLog

  • getLog(success?: (log: string) => void, failure?: (error: string) => void): Promise<string>
  • deprecated

    Use Logger.getLog.

    Parameters

    • Optional success: (log: string) => void
        • (log: string): void
        • Parameters

          • log: string

          Returns void

    • Optional failure: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<string>

Static getOdometer

  • getOdometer(success?: (odometer: number) => void, failure?: Function): Promise<number>
  • Retrieve the current distance-traveled ("odometer").

    The plugin constantly tracks distance traveled, computing the distance between the current location and last and maintaining the sum. To fetch the current odometer reading:

    example
    let odometer = await BackgroundGeolocation.getOdometer();
    

    ℹī¸ See also:

    ⚠ī¸ Warning:

    • Odometer calculations are dependent upon the accuracy of received locations. If location accuracy is poor, this will necessarily introduce error into odometer calculations.

    Parameters

    • Optional success: (odometer: number) => void
        • (odometer: number): void
        • Parameters

          • odometer: number

          Returns void

    • Optional failure: Function

    Returns Promise<number>

Static getProviderState

Static getSensors

  • getSensors(success?: (sensors: Sensors) => void, failure?: Function): Promise<Sensors>
  • Returns the presence of device sensors accelerometer, gyroscope, magnetometer

    break

    These core Sensors are used by the motion activity-recognition system -- when any of these sensors are missing from a device (particularly on cheap Android devices), the performance of the motion activity-recognition system will be severely degraded and highly inaccurate.

    For devices which are missing any of these sensors, you can increase the motion-detection sensitivity by decreasing minimumActivityRecognitionConfidence.

    example
    let sensors = await BackgroundGeolocation.sensors;
    console.log(sensors);
    

    Parameters

    • Optional success: (sensors: Sensors) => void
    • Optional failure: Function

    Returns Promise<Sensors>

Static getState

  • getState(success?: (state: State) => void, failure?: (error: string) => void): Promise<State>
  • Return the current State of the plugin, including all Config parameters.

    example
    let state = await BackgroundGeolocation.getState();
    console.log("[state] ", state.enabled, state.trackingMode);
    

    Parameters

    • Optional success: (state: State) => void
        • Parameters

          Returns void

    • Optional failure: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static insertLocation

Static isPowerSaveMode

  • isPowerSaveMode(success?: (enabled: boolean) => void, failure?: Function): Promise<boolean>
  • Fetches the state of the operating-system's "Power Saving" mode.

    break

    Power Saving mode can throttle certain services in the background, such as HTTP requests or GPS.

    ℹī¸ You can listen to changes in the state of "Power Saving" mode from the event onPowerSaveChange.

    iOS

    iOS Power Saving mode can be engaged manually by the user in Settings -> Battery or from an automatic OS dialog.

    Android

    Android Power Saving mode can be engaged manually by the user in Settings -> Battery -> Battery Saver or automatically with a user-specified "threshold" (eg: 15%).

    example
    let isPowerSaveMode = await BackgroundGeolocation.isPowerSaveMode;
    

    Parameters

    • Optional success: (enabled: boolean) => void
        • (enabled: boolean): void
        • Parameters

          • enabled: boolean

          Returns void

    • Optional failure: Function

    Returns Promise<boolean>

Static onAuthorization

Static onNotificationAction

  • onNotificationAction(callback: (buttonId: string) => void): Subscription
  • [Android-only] Subscribe to button-clicks of a custom Notification.layout on the Android foreground-service notification.

    Parameters

    • callback: (buttonId: string) => void
        • (buttonId: string): void
        • Parameters

          • buttonId: string

          Returns void

    Returns Subscription

Static playSound

  • playSound(soundId: any, success?: Function, failure?: Function): Promise<void>
  • Parameters

    • soundId: any
    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static ready

  • ready(config: Config, success?: (state: State) => void, failure?: (error: string) => void): Promise<State>
  • Signal to the plugin that your app is launched and ready, proving the default Config.

    The supplied Config will be applied only at first install of your app — for every launch thereafter, the plugin will automatically load its last-known configuration from persistent storage. The plugin always remembers the configuration you apply to it.

    example
    BackgroundGeolocation.ready({
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
      distanceFilter: 10,
      stopOnTerminate: false,
      startOnBoot: true,
      url: "http://your.server.com",
      headers: {
       "my-auth-token": "secret-token"
      }
    }).then((state) => {
     console.log("[ready] success", state);
    });
    

    ⚠ī¸ Warning: You must call #ready once and only once, each time your app is launched.

    • Do not hide the call to #ready within a view which is loaded only by clicking a UI action. This is particularly important for iOS in the case where the OS relaunches your app in the background when the device is detected to be moving. If you don't ensure that #ready is called in this case, tracking will not resume.

    The reset method.

    If you wish, you can use the reset method to reset all Config options to documented default-values (with optional overrides):

    example
    BackgroundGeolocation.reset();
    // Reset to documented default-values with overrides
    bgGeo.reset({
      distanceFilter:  10
    });
    

    Parameters

    • config: Config
    • Optional success: (state: State) => void
        • Parameters

          Returns void

    • Optional failure: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static registerHeadlessTask

  • registerHeadlessTask(callback: (event: Object) => Promise<void>): void
  • Registers a Javascript callback to execute in the Android "Headless" state, where the app has been terminated configured with stopOnTerminate:false. * The received event object contains a name (the event name) and params (the event data-object).

    ⚠ī¸ Note Cordova & Capacitor

    ⚠ī¸ Warning:

    • You must registerHeadlessTask in your application root file (eg: index.js).
    example
    const BackgroundGeolocationHeadlessTask = async (event) => {
      let params = event.params;
       console.log("[BackgroundGeolocation HeadlessTask] -", event.name, params);
    
       switch (event.name) {
         case "heartbeat":
           // Use await for async tasks
           let location = await BackgroundGeolocation.getCurrentPosition({
             samples: 1,
             persist: false
           });
           console.log("[BackgroundGeolocation HeadlessTask] - getCurrentPosition:", location);
           break;
       }
    }
    
    BackgroundGeolocation.registerHeadlessTask(BackgroundGeolocationHeadlessTask);
    

    ℹī¸ See also:

    Parameters

    • callback: (event: Object) => Promise<void>
        • (event: Object): Promise<void>
        • Parameters

          • event: Object

          Returns Promise<void>

    Returns void

Static removeAllListeners

  • removeAllListeners(success?: Function, failure?: Function): Promise<void>
  • Alias for removeListeners

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static removeGeofence

  • removeGeofence(identifier: string, success?: Function, failure?: Function): Promise<void>
  • Removes a Geofence having the given Geofence.identifier.

    example
    BackgroundGeolocation.removeGeofence("Home").then((success) => {
      console.log("[removeGeofence] success");
    }).catch((error) => {
      console.log("[removeGeofence] FAILURE: ", error);
    });
    

    ℹī¸ See also:

    Parameters

    • identifier: string
    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static removeGeofences

  • removeGeofences(success?: Function, failure?: Function): Promise<void>

Static removeListener

  • removeListener(event: string, handler: Function, success?: Function, failure?: Function): void
  • deprecated.

    Use Subscription returned from BackgroundGeolocation.onXXX to remove listeners.

    example
    const subscription = BackgroundGeolocation.onLocation((location) => {
      console.log('[onLocation]', location);
    });
    .
    .
    .
    // Remove listener
    subscription.remove();
    

    ⚠ī¸ [Deprecated]

    Removes an event listener. You must supply the type of event to remove in addition to a reference to the exact function you used to subscribe to the event.

    Event
    location
    motionchange
    activitychange
    providerchange
    geofence
    geofenceschange
    heartbeat
    http
    powersavechange
    schedule
    connectivitychange
    enabledchange
    example
    const locationHandler = (location) => {
      console.log("[location] - ", location)
    }
    BackgroundGeolocation.onLocation(locationHandler)
    .
    .
    // Remove the listener providing a reference to the original callback.
    BackgroundGeolocation.removeListener("location", locationHandler)
    

    Parameters

    • event: string
    • handler: Function
    • Optional success: Function
    • Optional failure: Function

    Returns void

Static removeListeners

  • removeListeners(success?: Function, failure?: Function): Promise<void>
  • Removes all event-listeners.

    Calls Subscription.remove on all subscriptions.

    example
    BackgroundGeolocation.removeListeners();
    

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static requestPermission

Static requestTemporaryFullAccuracy

  • [iOS 14+] iOS 14 has introduced a new [Precise: On] switch on the location authorization dialog allowing users to disable high-accuracy location.

    The method requestTemporaryFullAccuracy (Apple docs) will allow you to present a dialog to the user requesting temporary full accuracy for the lifetime of this application run (until terminate).

    Configuration — Info.plist

    In order to use this method, you must configure your Info.plist with the Dictionary key: Privacy - Location Temporary Usage Description Dictionary

    The keys of this Dictionary (eg: Delivery) are supplied as the first argument to the method. The value will be printed on the dialog shown to the user, explaing the purpose of your request for full accuracy.

    If the dialog fails to be presented, an error will be thrown:

    • The Info.plist file doesn’t have an entry for the given purposeKey value.
    • The app is already authorized for full accuracy.
    • The app is in the background.

    Note: Android and older versions of iOS < 14 will return BackgroundGeolocation.ACCURACY_AUTHORIZATION_FULL.

    example
    BackgroundGeolocation.onProviderChange((event) => {
      if (event.accuracyAuthorization == BackgroundGeolocation.ACCURACY_AUTHORIZATION_REDUCED) {
        // Supply "Purpose" key from Info.plist as 1st argument.
        BackgroundGeolocation.requestTemporaryFullAccuracy("Delivery").then((accuracyAuthorization) => {
          if (accuracyAuthorization == BackgroundGeolocation.ACCURACY_AUTHORIZATION_FULL) {
            console.log('[requestTemporaryFullAccuracy] GRANTED: ', accuracyAuthorization);
          } else {
            console.log('[requestTemporaryFullAccuracy] DENIED: ', accuracyAuthorization);
          }
        }).catch((error) => {
          console.warn("[requestTemporaryFullAccuracy] FAILED TO SHOW DIALOG: ", error);
        });
      }
    });
    

    See also:

    Parameters

    • purpose: string

    Returns Promise<AccuracyAuthorization>

Static reset

  • reset(config?: Config, success?: (state: State) => void, failure?: Function): Promise<State>
  • Resets the plugin configuration to documented default-values.

    If an optional Config is provided, it will be applied after the configuration reset.

    Parameters

    • Optional config: Config
    • Optional success: (state: State) => void
        • Parameters

          Returns void

    • Optional failure: Function

    Returns Promise<State>

Static resetOdometer

  • resetOdometer(success?: Function, failure?: Function): Promise<Location>
  • Initialize the odometer to 0.

    example
    BackgroundGeolocation.resetOdometer().then((location) => {
      // This is the location where odometer was set at.
      console.log("[setOdometer] success: ", location);
    });
    

    ⚠ī¸ Note:

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns Promise<Location>

Static setConfig

  • setConfig(config: Config, success?: (state: State) => void, failure?: Function): Promise<State>
  • Re-configure the SDK's Config parameters. This is the method to use when you wish to change the plugin Config after ready has been executed.

    The supplied Config will be appended to the current configuration and applied in realtime.

    example
    BackgroundGeolocation.setConfig({
      desiredAccuracy: Config.DESIRED_ACCURACY_HIGH,
      distanceFilter: 100.0,
      stopOnTerminate: false,
      startOnBoot: true
    }).then((state) => {
      console.log("[setConfig] success: ", state);
    })
    

    Parameters

    • config: Config
    • Optional success: (state: State) => void
        • Parameters

          Returns void

    • Optional failure: Function

    Returns Promise<State>

Static setLogLevel

  • setLogLevel(value: LogLevel, success?: (state: State) => void, failure?: Function): Promise<State>
  • Sets the logLevel.

    Parameters

    • value: LogLevel
    • Optional success: (state: State) => void
        • Parameters

          Returns void

    • Optional failure: Function

    Returns Promise<State>

Static setOdometer

  • setOdometer(value: number, success?: (location: Location) => void, failure?: Function): Promise<Location>
  • Initialize the odometer to any arbitrary value.

    example
    BackgroundGeolocation.setOdometer(1234.56).then((location) => {
      // This is the location where odometer was set at.
      console.log("[setOdometer] success: ", location);
    });
    

    ⚠ī¸ Note:

    Parameters

    • value: number
    • Optional success: (location: Location) => void
    • Optional failure: Function

    Returns Promise<Location>

Static start

  • start(success?: (state: State) => void, error?: (error: string) => void): Promise<State>
  • Enable location + geofence tracking.

    This is the SDK's power ON button. The plugin will initially start into its stationary state, fetching an initial location before turning off location services. Android will be monitoring its Activity Recognition System while iOS will create a stationary geofence around the current location.

    ⚠ī¸ Note:

    If you've configured a schedule, this method will override that schedule and engage tracking immediately.

    example
    BackgroundGeolocation.start().then((state) => {
      console.log("[start] success - ", state);
    });
    

    ℹī¸ See also:

    Parameters

    • Optional success: (state: State) => void
        • Parameters

          Returns void

    • Optional error: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static startBackgroundTask

  • startBackgroundTask(success?: (taskId: number) => void, failure?: Function): Promise<number>
  • Sends a signal to OS that you wish to perform a long-running task.

    The OS will keep your running in the background and not suspend it until you signal completion with the stopBackgroundTask method. Your callback will be provided with a single parameter taskId which you will send to the stopBackgroundTask method.

    example
    onLocation(location) {
      console.log("[location] ", location);
    
      // Perform some long-running task (eg: HTTP request)
      BackgroundGeolocation.startBackgroundTask().then((taskId) => {
        performLongRunningTask.then(() => {
          // When your long-running task is complete, signal completion of taskId.
          BackgroundGeolocation.stopBackgroundTask(taskId);
        }).catch(error) => {
          // Be sure to catch errors:  never leave you background-task hanging.
          console.error(error);
          BackgroundGeolocation.stopBackgroundTask();
        });
      });
    }
    

    iOS

    The iOS implementation uses beginBackgroundTaskWithExpirationHandler

    ⚠ī¸ iOS provides exactly 180s of background-running time. If your long-running task exceeds this time, the plugin has a fail-safe which will automatically stopBackgroundTask your taskId to prevent the OS from force-killing your application.

    Logging of iOS background tasks looks like this:

    ✅-[BackgroundTaskManager createBackgroundTask] 1
    .
    .
    .
    
    ✅-[BackgroundTaskManager stopBackgroundTask:]_block_invoke 1 OF (
        1
    )
    

    Android

    The Android implementation launches a WorkManager task.

    ⚠ī¸ The Android plugin imposes a limit of 3 minutes for your background-task before it automatically FORCE KILLs it.

    Logging for Android background-tasks looks like this (when you see an hourglass âŗ icon, a foreground-service is active)

     I TSLocationManager: [c.t.l.u.BackgroundTaskManager onStartJob] âŗ startBackgroundTask: 6
     .
     .
     .
     I TSLocationManager: [c.t.l.u.BackgroundTaskManager$Task stop] âŗ stopBackgroundTask: 6
    

    Parameters

    • Optional success: (taskId: number) => void
        • (taskId: number): void
        • Parameters

          • taskId: number

          Returns void

    • Optional failure: Function

    Returns Promise<number>

Static startGeofences

  • startGeofences(success?: (state: State) => void, failure?: (error: string) => void): Promise<State>
  • Engages the geofences-only State.trackingMode.

    In this mode, no active location-tracking will occur — only geofences will be monitored. To stop monitoring "geofences" TrackingMode, simply use the usual stop method.

    example
    // Add a geofence.
    BackgroundGeolocation.addGeofence({
      notifyOnExit: true,
      radius: 200,
      identifier: "ZONE_OF_INTEREST",
      latitude: 37.234232,
      longitude: 42.234234
    });
    
    // Listen to geofence events.
    BackgroundGeolocation.onGeofence((event) => {
      console.log("[onGeofence] -  ", event);
    });
    
    // Configure the plugin
    BackgroundGeolocation.ready({
      url: "http://my.server.com",
      autoSync: true
    }).then(((state) => {
      // Start monitoring geofences.
      BackgroundGeolocation.startGeofences();
    });
    

    ℹī¸ See also:

    Parameters

    • Optional success: (state: State) => void
        • Parameters

          Returns void

    • Optional failure: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static startSchedule

  • startSchedule(success?: (state: State) => void, failure?: (error: string) => void): Promise<State>
  • Initiate the configured schedule.

    If a schedule was configured, this method will initiate that schedule. The plugin will automatically be started or stopped according to the configured schedule.

    To halt scheduled tracking, use stopSchedule.

    example
    BackgroundGeolocation.startSchedule.then((state) => {
      console.log("[startSchedule] success: ", state);
    })
    

    ℹī¸ See also:

    Parameters

    • Optional success: (state: State) => void
        • Parameters

          Returns void

    • Optional failure: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static stop

  • stop(success?: (state: State) => void, error?: (error: string) => void): Promise<State>
  • Disable location and geofence monitoring. This is the SDK's power OFF button.

    example
    BackgroundGeolocation.stop();
    

    ⚠ī¸ Note:

    If you've configured a schedule, #stop will not halt the Scheduler. You must explicitly stopSchedule as well:

    example
    // Later when you want to stop the Scheduler (eg: user logout)
    BackgroundGeolocation.stopSchedule();
    

    Parameters

    • Optional success: (state: State) => void
        • Parameters

          Returns void

    • Optional error: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static stopBackgroundTask

  • stopBackgroundTask(taskId: number, success?: Function, failure?: Function): Promise<number>
  • Signal completion of startBackgroundTask

    Sends a signal to the native OS that your long-running task, addressed by taskId provided by startBackgroundTask is complete and the OS may proceed to suspend your application if applicable.

    example
    BackgroundGeolocation.startBackgroundTask().then((taskId) => {
      // Perform some long-running task (eg: HTTP request)
      performLongRunningTask.then(() => {
        // When your long-running task is complete, signal completion of taskId.
        BackgroundGeolocation.stopBackgroundTask(taskId);
      });
    });
    

    Parameters

    • taskId: number
    • Optional success: Function
    • Optional failure: Function

    Returns Promise<number>

Static stopSchedule

  • stopSchedule(success?: (state: State) => void, failure?: (error: string) => void): Promise<State>
  • Halt scheduled tracking.

    example
    BackgroundGeolocation.stopSchedule.then((state) => {
      console.log("[stopSchedule] success: ", state);
    })
    

    ⚠ī¸ stopSchedule will not execute stop if the plugin is currently tracking. You must explicitly execute stop.

    example
    // Later when you want to stop the Scheduler (eg: user logout)
    await BackgroundGeolocation.stopSchedule().then((state) => {
      if (state.enabled) {
        BackgroundGeolocation.stop();
      }
    })
    

    ℹī¸ See also:

    Parameters

    • Optional success: (state: State) => void
        • Parameters

          Returns void

    • Optional failure: (error: string) => void
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static stopWatchPosition

  • stopWatchPosition(success?: Function, failure?: Function): Promise<void>
  • Stop watch-position updates initiated from watchPosition.

    example
    onResume() {
      // Start watching position while app in foreground.
      BackgroundGeolocation.watchPosition((location) => {
        console.log("[watchPosition] -", location);
      }, (errorCode) => {
        console.log("[watchPosition] ERROR -", errorCode);
      }, {
       interval: 1000
      })
    }
    
    onSuspend() {
      // Halt watching position when app goes to background.
      BackgroundGeolocation.stopWatchPosition();
    }
    

    ℹī¸ See also:

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static sync

  • sync(success?: (locations: Object[]) => void, failure?: Function): Promise<Object[]>
  • Manually execute upload to configured Config.url

    If the plugin is configured for HTTP with an Config.url and autoSync false, the sync method will initiate POSTing the locations currently stored in the native SQLite database to your configured Config.url. When your HTTP server returns a response of 200 OK, that record(s) in the database will be DELETED.

    If you configured batchSync true, all the locations will be sent to your server in a single HTTP POST request, otherwise the plugin will execute an HTTP post for each Location in the database (REST-style). Your callback will be executed and provided with a List of all the locations from the SQLite database. If you configured the plugin for HTTP (by configuring a Config.url, your callback will be executed after all the HTTP request(s) have completed. If the plugin failed to sync to your server (possibly because of no network connection), the failure callback will be called with an error message. If you are not using the HTTP features, sync will delete all records from its SQLite database.

    example
    BackgroundGeolocation.sync((records) => {
      console.log("[sync] success: ", records);
    }).catch((error) => {
      console.log("[sync] FAILURE: ", error);
    });
    
    

    ℹī¸ For more information, see the HTTP Guide

    Parameters

    • Optional success: (locations: Object[]) => void
        • (locations: Object[]): void
        • Parameters

          • locations: Object[]

          Returns void

    • Optional failure: Function

    Returns Promise<Object[]>

Static transistorTrackerParams

  • transistorTrackerParams(device: Object): Object

Static watchPosition

  • Start a stream of continuous location-updates. The native code will persist the fetched location to its SQLite database just as any other location (If the SDK is currently State.enabled) in addition to POSTing to your configured Config.url (if you've enabled the HTTP features).

    ⚠ī¸ Warning:

    watchPosition is not recommended for long term monitoring in the background — It's primarily designed for use in the foreground only. You might use it for fast-updates of the user's current position on the map, for example. The SDK's primary Philosophy of Operation does not require watchPosition.

    iOS

    watchPosition will continue to run in the background, preventing iOS from suspending your application. Take care to listen to suspend event and call stopWatchPosition if you don't want your app to keep running in the background, consuming battery.

    example
    onResume() {
      // Start watching position while app in foreground.
      BackgroundGeolocation.watchPosition((location) => {
        console.log("[watchPosition] -", location);
      }, (errorCode) => {
        console.log("[watchPosition] ERROR -", errorCode);
      }, {
        interval: 1000
      })
    }
    
    onSuspend() {
      // Halt watching position when app goes to background.
      BackgroundGeolocation.stopWatchPosition();
    }
    

    Parameters

    Returns void

Generated using TypeDoc