@capgo/background-geolocation

中文文档
8.5.2发布于 2026/11/02MPL-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 17.1万

Accurate background geolocation and native geofencing for Capacitor apps on iOS and Android.

原始使用文档
文档目录34 节
  1. ➡️ Get started for free
  2. Key features
  3. Features
  4. This plugin's history
  5. Plugin comparison
  6. Usage
  7. Native geofencing
  8. Android background geofence permission
  9. Location log
  10. Optional SQLite location log
  11. Documentation
  12. Compatibility
  13. Installation
  14. iOS
  15. Android
  16. API
  17. start(...)
  18. stop()
  19. updateHeaders(...)
  20. openSettings()
  21. setPlannedRoute(...)
  22. setupGeofencing(...)
  23. addGeofence(...)
  24. removeGeofence(...)
  25. removeAllGeofences()
  26. getMonitoredGeofences()
  27. getLocationLog(...)
  28. clearLocationLog(...)
  29. addListener('geofenceTransition', ...)
  30. addListener('geofenceError', ...)
  31. checkPermissions()
  32. requestPermissions(...)
  33. getPluginVersion()
  34. Interfaces

Background Geolocation

Track precise location in the background and monitor native geofences on iOS and Android. Built for delivery, fitness and field service apps that keep tracking when the screen is off.

Capgo - Build Capacitor apps with AI, ship updates instantly

Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.

➡️ Get started for free

14-day unlimited free trial. No credit card required

🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use @capgo/background-geolocation in your Capacitor app: npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/background-geolocation to my Capacitor app and wire it up." Agent setup guides · Hosted MCP

@capgo/background-geolocation for Capacitor apps

Key features

  • Background tracking: start() streams location updates with options such as distanceFilter and a background notification message, stop() ends them.
  • Native uploads: send locations to your url from native code, and change headers on the fly with updateHeaders().
  • Geofencing: addGeofence(), removeGeofence(), removeAllGeofences() and getMonitoredGeofences(), with geofenceTransition and geofenceError events.
  • Route guidance: setPlannedRoute() plays a sound when the user leaves a planned route.
  • Permissions: checkPermissions(), requestPermissions() and openSettings().
  • Platforms: iOS and Android. iOS uses Core Location, Android uses Google Play services location with a foreground service.

A Capacitor plugin for accurate background location tracking and native geofencing on iOS and Android. Use it to stream precise location updates, monitor circular geofence regions, react to enter/exit events in JavaScript, and POST geofence transitions natively while the WebView is suspended.

Features

  • Accurate foreground and background geolocation without a paid license.
  • Native geofencing on iOS and Android for circular regions.
  • Enter and exit events through geofenceTransition while the app is alive.
  • Native webhook delivery for geofence transitions when the WebView is suspended.
  • A web fallback for development and browser-based testing.

This plugin's history

Interestingly enough, this plugin has a lot of history. The initial solution from Transistorsoft was a great piece of software, and I (HarelM) encourage using it if it fits your needs.
I tried it and understood that it prioritizes battery life over accuracy, which wasn't the right fit for my hiking app.
There was a very good fork maintained by mauron85 specifically for that use case, and I was happy to help maintain it.
But at some point, mauron85 stopped responding to messages on GitHub, and no one could continue maintaining it.
I hope mauron85 is safe and sound somewhere.

So I created a fork and started maintaining it here.
It served me well for over half a decade, but I felt it was hard to maintain due to all its history, features, and bug fixes.
I also felt like there was a barrier to introducing new features because of its complexity.

So I started exploring what it would take to reduce that complexity, at the same time, I was envious of how small @capacitor-community/background-geolocation is.
I took the best of both worlds: tried to reduce the codebase in the original Cordova plugin and add some robustness to the Capacitor plugin.

That's how I ended up maintaining this one.
I hope you'll enjoy it!

Plugin comparison

A short comparison between the three main background-geolocation plugins commonly used in Capacitor apps.

PluginAccuracyBackgroundGeofencingNative transition POSTPricing
@capacitor-community/background-geolocation (Community)Not accurateYesNoNoFree
@capgo/background-geolocation (this plugin)AccurateYesiOS and AndroidYes, for geofence transitionsFree
Transistorsoft (original)AccurateYesYesYes, built-in HTTP uploaderPaid

Notes:

  • The Community plugin is lightweight and continues to work in the background, but it is known to be less accurate than the options below.
  • This Cap-go plugin aims to provide accurate location fixes, reliable background operation, and native geofence enter/exit handling without requiring a paid license.
  • Native geofence POST delivery is useful when iOS or Android wakes native code for a region transition but the Capacitor WebView is not running.
  • Transistorsoft's plugin is a mature, accurate solution that also includes a broader HTTP uploader. It is a commercial product and requires a paid license for full use.

Usage

import { BackgroundGeolocation } from "@capgo/background-geolocation";

BackgroundGeolocation.start(
    {
        backgroundMessage: "Cancel to prevent battery drain.",
        backgroundTitle: "Tracking You.",
        requestPermissions: true,
        stale: false,
        distanceFilter: 50
    },
    (location, error) => {
        if (error) {
            if (error.code === "NOT_AUTHORIZED") {
                if (window.confirm(
                    "This app needs your location, " +
                    "but does not have permission.\n\n" +
                    "Open settings now?"
                )) {
                    // It can be useful to direct the user to their device's
                    // settings when location permissions have been denied. The
                    // plugin provides the 'openSettings' method to do exactly
                    // this.
                    BackgroundGeolocation.openSettings();
                }
            }
            return console.error(error);
        }
        return console.log(location);
    }
).then(() => {
    // When location updates are no longer needed, the plugin should be stopped by calling
    BackgroundGeolocation.stop();
});

// Set a planned route to get a notification sound when a new location arrives and it's not on the route:
        
BackgroundGeolocation.setPlannedRoute({soundFile: "assets/myFile.mp3", route: [[1,2], [3,4]], distance: 30 });

Native geofencing

Use native geofencing when you need lightweight location boundaries such as stores, job sites, delivery zones, campuses, or check-in areas. The plugin monitors geofences natively and emits JavaScript events while the app is active. Android background delivery is optional and only requested when you opt in.

import { BackgroundGeolocation } from "@capgo/background-geolocation";

// Geofencing can notify JavaScript while the app is alive.
await BackgroundGeolocation.setupGeofencing({
    notifyOnEntry: true,
    notifyOnExit: true,
    payload: { userId: "123" }
});

await BackgroundGeolocation.addGeofence({
    identifier: "office",
    latitude: 37.33182,
    longitude: -122.03118,
    radius: 150
});

const handle = await BackgroundGeolocation.addListener(
    "geofenceTransition",
    (event) => console.log(event.identifier, event.transition)
);

await BackgroundGeolocation.removeGeofence({ identifier: "office" });
handle.remove();

Android background geofence permission

The plugin does not add ACCESS_BACKGROUND_LOCATION by default and does not request it unless you explicitly opt in. Apps that only use foreground location can omit this permission.

Opt in only when you need Android geofence transitions while the app is in the background:

<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
await BackgroundGeolocation.setupGeofencing({
    url: "https://api.example.com/geofences",
    backgroundLocation: true
});
// If you just want the current location, try something like this. The longer
// the timeout, the more accurate the guess will be. I wouldn't go below about 100ms.
function guessLocation(callback, timeout) {
    let last_location;
    BackgroundGeolocation.start(
        {
            requestPermissions: false,
            stale: true
        },
        (location) => {
            last_location = location || undefined;
        }
    ).then(() => {
        setTimeout(() => {
            callback(last_location);
            BackgroundGeolocation.stop();
        }, timeout);
    });
}

Location log

The callback only runs while the WebView does, and a location POSTed to url is dropped when its request fails. With locationLog on, every location is also added to a file on the device. It's written from native code, so it records for as long as tracking runs, and it survives app restarts and reboots.

await BackgroundGeolocation.start(
    {
        backgroundMessage: "Sharing your location.",
        locationLog: true
    },
    (location, error) => console.log(location, error)
);

// Later, when the app returns to the foreground or the network is back
const { entries } = await BackgroundGeolocation.getLocationLog();
if (entries.length > 0) {
    // Use the entries, for example upload them, then remove the ones that were read
    await BackgroundGeolocation.clearLocationLog({ upToId: entries[entries.length - 1].id });
}

Each entry is a Location with an id. The ids only go up, so clearing with upToId never removes a location that arrived after the read. The log holds up to locationLogMaxEntries locations, and limit and afterId read it in pages. It's left out of device backups, so on a restored device it starts empty and the ids start again at 1.

Optional SQLite location log

The default build stores the log in a rolling file and does not compile SQLite code. To opt in to the SQLite backend (POST status per entry, same model as the original PR #92), set this in capacitor.config and run npx cap sync:

plugins: {
  BackgroundGeolocation: {
    locationLogSqlite: true
  }
}

Then pass locationLogSqlite: true in start() together with locationLog: true. If you request locationLogSqlite without enabling it in capacitor.config, start() rejects with a clear error.

On iOS, npx cap sync toggles the optional ios/SqliteLocationLog sources in the podspec and adds those sources plus sqlite3 to the main SPM target in Package.swift (default checkout does not compile or link SQLite). On Android, sync sets backgroundGeolocation.locationLogSqlite.include in android/gradle.properties.

To confirm the default dependency graph excludes SQLite: cd android && ./gradlew :dependencies --configuration releaseCompileClasspath (no sqliteEnabled sources), and in Package.swift / CapgoBackgroundGeolocation.podspec the SQLite lines stay commented until sync enables them.

Documentation

The most complete doc is available here: https://capgo.app/docs/plugins/background-geolocation/

Compatibility

Plugin versionCapacitor compatibilityMaintained
v8.*.*v8.*.*✅
v7.*.*v7.*.*On demand
v6.*.*v6.*.*❌
v5.*.*v5.*.*❌

Note: The major version of this plugin follows the major version of Capacitor. Use the version that matches your Capacitor installation (e.g., plugin v8 for Capacitor 8). Only the latest major version is actively maintained.

Installation

You can use our AI-Assisted Setup to install the plugin. Add the Capgo skills to your AI tool using the following command:

npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-plugins

Then use the following prompt:

Use the `capacitor-plugins` skill from `cap-go/capacitor-skills` to install the `@capgo/background-geolocation` plugin in my project.

If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:

This plugin supports Capacitor v8:

CapacitorPlugin
v8v8
bun add @capgo/background-geolocation
bunx cap update

iOS

Add the following keys to Info.plist.:

<dict>
  ...
  <key>NSLocationWhenInUseUsageDescription</key>
  <string>We need to track your location</string>
  <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  <string>We need to track your location while your device is locked.</string>
  <key>UIBackgroundModes</key>
  <array>
    <string>location</string>
  </array>
  ...
</dict>

Android

Set the the android.useLegacyBridge option to true in your Capacitor configuration. This prevents location updates halting after 5 minutes in the background. See https://capacitorjs.com/docs/config and https://github.com/capacitor-community/background-geolocation/issues/89.

On Android 13+, the app needs the POST_NOTIFICATIONS runtime permission to show the persistent notification informing the user that their location is being used in the background. This runtime permission is requested after the location permission is granted.

For background geofencing on Android 10+, the app also needs ACCESS_BACKGROUND_LOCATION and backgroundLocation: true in setupGeofencing(). Android may require the user to grant this from system settings after foreground location is granted; use openSettings() if the permission remains denied. Leave backgroundLocation unset or false if your app does not have Google Play approval for Android background location.

If your app forwards location updates to a server in real time, be aware that after 5 minutes in the background Android will throttle HTTP requests initiated from the WebView. The solution is to use a native HTTP plugin such as CapacitorHttp. See https://github.com/capacitor-community/background-geolocation/issues/14.

Configuration specific to Android can be made in strings.xml:

<resources>
    <!--
        The channel name for the background notification. This will be visible
        when the user presses & holds the notification. It defaults to
        "Background Tracking".
    -->
    <string name="capacitor_background_geolocation_notification_channel_name">
        Background Tracking
    </string>

    <!--
        The icon to use for the background notification. Note the absence of a
        leading "@". It defaults to "mipmap/ic_launcher", the app's launch icon.

        If a raster image is used to generate the icon (as opposed to a vector
        image), it must have a transparent background. To make sure your image
        is compatible, select "Notification Icons" as the Icon Type when
        creating the image asset in Android Studio.

        An incompatible image asset will cause the notification to misbehave in
        a few telling ways, even if the icon appears correctly:

          - The notification may be dismissable by the user when it should not
            be.
          - Tapping the notification may open the settings, not the app.
          - The notification text may be incorrect.
    -->
    <string name="capacitor_background_geolocation_notification_icon">
        drawable/ic_tracking
    </string>

    <!--
        The color of the notification as a string parseable by
        android.graphics.Color.parseColor. Optional.
    -->
    <string name="capacitor_background_geolocation_notification_color">
        yellow
    </string>
</resources>

API

Main plugin interface for background geolocation functionality. Provides methods to manage location updates and access device settings.

start(...)

start(options: StartOptions, callback: (position?: Location | undefined, error?: CallbackError | undefined) => void) => Promise<void>

To start listening for changes in the device's location, call this method. A Promise is returned to indicate that it finished the call. The callback will be called every time a new location is available, or if there was an error when calling this method. Don't rely on promise rejection for this.

ParamTypeDescription
optionsStartOptionsThe configuration options
callback(position?: Location, error?: CallbackError) => voidThe callback function invoked when a new location is available or an error occurs

Since: 7.0.9


stop()

stop() => Promise<void>

Stops location updates.

Since: 7.0.9


updateHeaders(...)

updateHeaders(options: UpdateHeadersOptions) => Promise<void>

Replaces HTTP headers used by native POSTs without restarting tracking.

Use this when an access token expires while url delivery is active. Headers apply to the running location watcher and to geofence setup when those features have a configured url.

ParamTypeDescription
optionsUpdateHeadersOptionsThe replacement headers

Since: 8.3.3


openSettings()

openSettings() => Promise<void>

Opens the device's location settings page. Useful for directing users to enable location services or adjust permissions.

Since: 7.0.0


setPlannedRoute(...)

setPlannedRoute(options: SetPlannedRouteOptions) => Promise<void>

Plays a sound file when the user deviates from the planned route. This should be used to play a sound (in the background too, only for native).

ParamTypeDescription
optionsSetPlannedRouteOptionsThe options for setting the planned route and sound file

Since: 7.0.11


setupGeofencing(...)

setupGeofencing(options: GeofenceSetupOptions) => Promise<void>

Configures native geofence transition handling.

Call this before adding geofences when you need default entry/exit settings or native background POSTs. Android background POSTs require backgroundLocation: true.

ParamTypeDescription
optionsGeofenceSetupOptionsThe geofence configuration options

Since: 8.0.30


addGeofence(...)

addGeofence(options: AddGeofenceOptions) => Promise<void>

Starts monitoring a circular native geofence.

ParamTypeDescription
optionsAddGeofenceOptionsThe geofence region options

Since: 8.0.30


removeGeofence(...)

removeGeofence(options: RemoveGeofenceOptions) => Promise<void>

Stops monitoring one geofence.

ParamTypeDescription
optionsRemoveGeofenceOptionsThe geofence identifier

Since: 8.0.30


removeAllGeofences()

removeAllGeofences() => Promise<void>

Stops monitoring every geofence registered by this plugin.

Since: 8.0.30


getMonitoredGeofences()

getMonitoredGeofences() => Promise<MonitoredGeofencesResult>

Lists the geofence identifiers currently monitored by this plugin.

Returns: Promise<MonitoredGeofencesResult>

Since: 8.0.30


getLocationLog(...)

getLocationLog(options?: GetLocationLogOptions | undefined) => Promise<LocationLogResult>

Reads the locations kept by {@link StartOptions.locationLog}, whether or not tracking is running. Nothing is kept on the web, so the result is empty there.

ParamTypeDescription
optionsGetLocationLogOptionsPaging for the entries to return

Returns: Promise<LocationLogResult>

Since: 8.5.0


clearLocationLog(...)

clearLocationLog(options?: ClearLocationLogOptions | undefined) => Promise<void>

Removes entries from the location log, for example once they have been read or uploaded.

ParamTypeDescription
optionsClearLocationLogOptionsWhich entries to remove

Since: 8.5.0


addListener('geofenceTransition', ...)

addListener(eventName: 'geofenceTransition', listenerFunc: (event: GeofenceTransitionEvent) => void) => Promise<PluginListenerHandle>

Listens for geofence enter/exit transitions while the WebView is alive.

Native url delivery configured through setupGeofencing is used for background-safe delivery.

ParamType
eventName'geofenceTransition'
listenerFunc(event: GeofenceTransitionEvent) => void

Returns: Promise<PluginListenerHandle>

Since: 8.0.30


addListener('geofenceError', ...)

addListener(eventName: 'geofenceError', listenerFunc: (event: GeofenceErrorEvent) => void) => Promise<PluginListenerHandle>

Listens for native geofence monitoring errors while the WebView is alive.

ParamType
eventName'geofenceError'
listenerFunc(event: GeofenceErrorEvent) => void

Returns: Promise<PluginListenerHandle>

Since: 8.0.30


checkPermissions()

checkPermissions() => Promise<BackgroundGeolocationPermissionStatus>

Read current location authorization without prompting or side effects.

On iOS this maps CLAuthorizationStatus so you can distinguish Always from While Using App. On Android this reports foreground location, ACCESS_BACKGROUND_LOCATION, and notification permission where relevant.

Returns: Promise<BackgroundGeolocationPermissionStatus>

Since: 8.0.43


requestPermissions(...)

requestPermissions(options?: RequestBackgroundGeolocationPermissionsOptions | undefined) => Promise<BackgroundGeolocationPermissionStatus>

Request location-related permissions from the user.

Prefer {@link BackgroundGeolocationPlugin.checkPermissions} for read-only status in settings screens. Call this only when the user has opted in.

ParamTypeDescription
optionsRequestBackgroundGeolocationPermissionsOptionsOptional subset of permissions to request

Returns: Promise<BackgroundGeolocationPermissionStatus>

Since: 8.0.43


getPluginVersion()

getPluginVersion() => Promise<{ version: string; }>

Get the native Capacitor plugin version

Returns: Promise<{ version: string; }>


Interfaces

StartOptions

The options for configuring for location updates.

PropTypeDescriptionDefaultSince
backgroundMessagestringIf the "backgroundMessage" option is defined, the plugin will provide location updates whether the app is in the background or the foreground. If it is not defined, location updates are only guaranteed in the foreground. This is true on both platforms. On Android, a notification must be shown to continue receiving location updates in the background. This option specifies the text of that notification.7.0.9
backgroundTitlestringThe title of the notification mentioned above."Using your location"7.0.9
requestPermissionsbooleanWhether permissions should be requested from the user automatically, if they are not already granted.true7.0.9
stalebooleanIf "true", stale locations may be delivered while the device obtains a GPS fix. You are responsible for checking the "time" property. If "false", locations are guaranteed to be up to date.false7.0.9
distanceFilternumberThe distance in meters that the device must move before a new location update is triggered. This is used to filter out small movements and reduce the number of updates. A non-zero value suppresses updates while the device is stationary (for example a parked vehicle). Use {@link StartOptions.minIntervalMs} when you need a lower update rate but still want periodic points without movement.07.0.9
urlstringWhen set, each location update is additionally delivered by POSTing it as JSON to this URL directly from native code, in parallel with the JavaScript callback. The request body matches the Location object, plus an extra "source": "native" field so the server can tell native POSTs apart from updates forwarded by the JavaScript layer. Native delivery does not depend on the WebView. On Android, the foreground service is kept alive and restarted by the system (START_STICKY), so location POSTs continue even after the user swipes the app away from the recents list and its process is killed. On iOS, locations are POSTed natively for as long as the system keeps the app running; iOS itself stops location updates when the user terminates the app (an OS restriction — iOS has no equivalent of Android's restartable foreground service). Delivery is best-effort: there is no on-disk queue and no automatic retry. Failed POSTs are logged and dropped. A flaky network can delay in-flight requests, but points are not persisted across process death. Set {@link StartOptions.locationLog} to keep every location on the device.8.2.0
headersRecord<string, string>Extra HTTP headers for the native POST described by {@link StartOptions.url}. Ignored when url is not set. On Android these headers are persisted next to url so a sticky service restart can keep authenticating. Prefer a narrowly scoped, long-lived token for this path, or call {@link BackgroundGeolocationPlugin.updateHeaders} when credentials rotate. On iOS location headers stay in memory for the tracking session.8.3.3
minIntervalMsnumberMinimum interval between native location POSTs, in milliseconds. 0 or unset keeps the current behaviour (every provider update). Applied as the Android requestLocationUpdates interval (advisory) and as a hard gate immediately before each native POST on both platforms. A point older than the last one sent still passes through (late update, not a faster one). Note: a non-zero {@link StartOptions.distanceFilter} suppresses updates while the device is stationary, so it cannot substitute for a time interval when you still need periodic parked-vehicle heartbeats.08.3.3
networkFallbackbooleanAndroid only - has no effect on iOS. Whether to fall back to NETWORK_PROVIDER (cell/Wi-Fi based location) when GPS_PROVIDER has not delivered a fix recently. GPS can go quiet for extended periods when the app is backgrounded, the screen is locked, or the device has weak sky visibility (indoors, dense urban areas); the network fallback fills those gaps with a coarser, but far more reliably delivered, fix. GPS always takes priority: a network fix is only used once GPS has been silent for 20+ seconds, and is dropped if its reported accuracy is worse than 300m or unreported. Defaults to false, so existing GPS-only accuracy characteristics are unchanged unless you opt in.false8.5.0
locationLogbooleanWhether every location is also added to a log file on the device. The file is written from native code, so it keeps recording while the WebView is suspended, and it survives stop(), app restarts and reboots. It is left out of device backups. Read it with {@link BackgroundGeolocationPlugin.getLocationLog}. Tracking, and the log with it, ends when the app is closed, except on Android with {@link StartOptions.url} set.false8.5.0
locationLogMaxEntriesnumberHow many locations the location log holds. Once it is full, the oldest tenth is removed. A location takes about 200 bytes.1000008.5.0
locationLogSqlitebooleanUse the optional SQLite location log backend instead of the default file log. Requires plugins.BackgroundGeolocation.locationLogSqlite: true in capacitor.config and npx cap sync so native SQLite code is included.false8.5.0

Location

Represents a geographical location with various attributes. Contains all the standard location properties returned by GPS/network providers.

PropTypeDescriptionSince
latitudenumberLatitude in degrees. Range: -90.0 to +90.07.0.0
longitudenumberLongitude in degrees. Range: -180.0 to +180.07.0.0
accuracynumberRadius of horizontal uncertainty in metres, with 68% confidence. Lower values indicate more accurate location.7.0.0
altitudenumber | nullMetres above sea level (or null if not available).7.0.0
altitudeAccuracynumber | nullVertical uncertainty in metres, with 68% confidence (or null if not available).7.0.0
simulatedbooleantrue if the location was simulated by software, rather than GPS. Useful for detecting mock locations in development or testing.7.0.0
bearingnumber | nullDeviation from true north in degrees (or null if not available). Range: 0.0 to 360.07.0.0
speednumber | nullSpeed in metres per second (or null if not available).7.0.0
timenumber | nullTime the location was produced, in milliseconds since the unix epoch. Use this to check if a location is stale when using stale: true.7.0.0

CallbackError

Error object that may be passed to the location start callback. Extends the standard Error with optional error codes.

PropTypeDescriptionSince
codestringOptional error code for more specific error handling.7.0.0

UpdateHeadersOptions

Options for {@link BackgroundGeolocationPlugin.updateHeaders}.

PropTypeDescriptionSince
headersRecord<string, string>Replacement HTTP headers for native POSTs configured via url. Applies to an active location watcher and to geofence setup when those features have a url. Pass an empty object to clear custom headers.8.3.3

SetPlannedRouteOptions

PropTypeDescriptionDefaultSince
soundFilestringThe name of the sound file to play. Must be a valid sound relative path in the app's public folder to work for both web and native platforms. There's no need to include the public folder in the path.7.0.10
route[number, number][]The planned route as an array of longitude and latitude pairs. Each pair represents a point on the route. This is used to define a route that the user can follow. The route is used to play a sound when the user deviates from it.7.0.11
distancenumberThe distance in meters that the user must deviate from the planned route to trigger the sound. This is used to determine how far off the route the user can be before the sound is played. If not specified, a default value of 50 meters is used.507.0.11

GeofenceSetupOptions

Options for configuring native geofence transition handling.

When url is provided, native code can send a JSON POST whenever a monitored region is entered or exited. Android background POST delivery requires backgroundLocation: true.

PropTypeDescriptionDefaultSince
urlstringEndpoint that receives geofence transition payloads. On Android, native background POST delivery requires backgroundLocation: true. Delivery is best-effort: there is no on-disk queue and no automatic retry. Failed POSTs are logged and dropped.8.0.30
headersRecord<string, string>Extra HTTP headers for the native POST described by {@link GeofenceSetupOptions.url}. Ignored when url is not set. Headers are persisted with the geofence setup so transitions that fire after process restart can still authenticate. Prefer a narrowly scoped token, or call {@link BackgroundGeolocationPlugin.updateHeaders} when credentials rotate.8.3.3
notifyOnEntrybooleanWhether entry transitions should be monitored.true8.0.30
notifyOnExitbooleanWhether exit transitions should be monitored.true8.0.30
payloadRecord<string, unknown>Base JSON payload merged into every native transition POST and listener event.8.0.30
requestPermissionsbooleanWhether the plugin should request the native location permission needed for geofencing. iOS geofencing needs Always location authorization. Android geofencing requests foreground location by default. Android background location is only requested when backgroundLocation is enabled.true8.0.30
backgroundLocationbooleanWhether Android geofencing should opt into background location permission. The plugin does not add ACCESS_BACKGROUND_LOCATION to your app manifest. Leave this disabled if your app does not have Google Play approval for Android background location. Enable it only after adding ACCESS_BACKGROUND_LOCATION to your app manifest and when you need Android geofence transitions while the app is in the background. This option only affects Android. Android versions below 10 do not request an extra background-location runtime permission, but the option still gates native Android background geofence delivery.false8.0.34

AddGeofenceOptions

A circular geofence region.

PropTypeDescriptionDefaultSince
latitudenumberLatitude in degrees for the region center.8.0.30
longitudenumberLongitude in degrees for the region center.8.0.30
radiusnumberRegion radius in meters.508.0.30
identifierstringStable identifier for the geofence.8.0.30
notifyOnEntrybooleanOverrides the setup-level entry setting for this region.8.0.30
notifyOnExitbooleanOverrides the setup-level exit setting for this region.8.0.30
payloadRecord<string, unknown>Region-specific payload merged over the setup payload.8.0.30

RemoveGeofenceOptions

Options for removing a monitored geofence.

PropTypeDescriptionSince
identifierstringIdentifier passed to addGeofence.8.0.30

MonitoredGeofencesResult

Result returned when listing monitored geofences.

PropTypeDescriptionSince
regionsstring[]Identifiers for all geofences currently monitored by this plugin.8.0.30

LocationLogResult

Result returned by {@link BackgroundGeolocationPlugin.getLocationLog}.

PropTypeDescriptionSince
entriesLocationLogEntry[]The entries, oldest first.8.5.0

LocationLogEntry

A location kept in the location log.

PropTypeDescriptionSince
idnumberIdentifier of the entry. Identifiers increase with every location and are never reused, so the last one read works as a cursor for {@link GetLocationLogOptions.afterId} and {@link ClearLocationLogOptions.upToId}.8.5.0
status'pending' | 'sent' | 'failed'Delivery status when using the SQLite location log backend.8.5.0
httpStatusnumber | nullHTTP status from the native POST when status is sent or failed.8.5.0
errorstring | nullError message when status is failed.8.5.0

GetLocationLogOptions

Options for {@link BackgroundGeolocationPlugin.getLocationLog}.

PropTypeDescriptionDefaultSince
afterIdnumberOnly return entries with an id greater than this one.8.5.0
limitnumberMaximum number of entries to return, up to 10000. Call again with afterId set to the last id received to read the next page.10008.5.0

ClearLocationLogOptions

Options for {@link BackgroundGeolocationPlugin.clearLocationLog}.

| Prop | Type | Description

版本与发布记录

@capgo/background-geolocation 共发布 89 个版本,首次发布于 2025/07/29;过去 12 个月发布了 69 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.5.2latest2026/11/026 天前
8.5.12026/11/027 天前
8.5.02026/10/2713 天前
8.4.142026/10/1525 天前
8.4.132026/10/1327 天前
8.4.122026/10/1228 天前

关于 @capgo/background-geolocation 的常见问题

@capgo/background-geolocation 是什么?

Accurate background geolocation and native geofencing for Capacitor apps on iOS and Android.

如何安装 @capgo/background-geolocation?

在项目目录运行 npm install @capgo/background-geolocation,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capgo/background-geolocation 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@capgo/background-geolocation 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capgo/background-geolocation 可以商用吗?

@capgo/background-geolocation 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@capgo/background-geolocation 的下载量有多少?

根据 npm 官方下载统计,@capgo/background-geolocation 在 2026/10/09 – 2026/11/07 这 30 天内被下载 170,899 次,日均约 5,697 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@capgo/background-geolocation 还在维护吗?

最新版本 8.5.2 发布于 2026/11/02(6 天前);至今共发布 89 个版本,其中过去 12 个月发布了 69 个;首次发布于 2025/07/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。