跳转到正文

快速入门

GitHub

@capgo/background-geolocation 将精准的后台位置追踪与 iOS 和 Android 原生地理围栏(geofencing)相结合。适用于配送区域、门店、作业现场、校园、签到、路线提醒,以及任何即使在 WebView 未运行时也需要进入或退出事件的工作流。

你可以使用我们的 AI 辅助设置来安装插件。使用以下命令将 Capgo skills 添加到你的 AI 工具中:

终端窗口
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

然后使用以下 prompt:

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

如果你更想手动设置,请运行以下命令安装插件,并按照下方各平台的说明操作:

终端窗口
bun add @capgo/background-geolocation
bunx cap sync
import { BackgroundGeolocation } from '@capgo/background-geolocation';

请求后台定位权限,使用用户可见的 Android 通知消息启动定位更新,并从原生 code 向你的 API POST 定位数据。

import { BackgroundGeolocation } from '@capgo/background-geolocation';
await BackgroundGeolocation.requestPermissions({
permissions: ['location', 'backgroundLocation', 'notification'],
});
await BackgroundGeolocation.start(
{
backgroundMessage: 'Tracking delivery route',
backgroundTitle: 'Location active',
requestPermissions: true,
stale: false,
url: 'https://api.example.com/locations',
headers: { Authorization: 'Bearer fleet-token' },
distanceFilter: 25,
},
(location, error) => {
if (error) {
console.error('Location error', error);
return;
}
if (location) {
console.log('Fix', location.latitude, location.longitude);
}
},
);

每个定位结果都会并行传递给 JavaScript(WebView 存活期间)以及 url 配合 "source": "native" 在 JSON body 中。

await BackgroundGeolocation.setupGeofencing({
url: 'https://api.example.com/geofence-hit',
backgroundLocation: true,
});

在 Android 上,声明 ACCESS_BACKGROUND_LOCATION 当需要后台地理围栏 POST 请求时,请在 manifest 中声明(参见下文的原生地理围栏章节)。

await BackgroundGeolocation.addGeofence({
identifier: 'warehouse',
latitude: 32.7,
longitude: -117.1,
radius: 200,
});
await BackgroundGeolocation.stop();
  • Android 通知:后台更新需要 backgroundMessage (及标题),让用户了解定位为何处于活动状态。
  • 过期的定位结果:设置 stale: false 当您只需要最新的 GPS 定位结果时。
  • 权限: 请求 backgroundLocation 在现代 Android 版本上需要分别请求。

调用此方法即可开始监听设备位置变化。 返回的 Promise 表示调用已完成。每次有新位置可用,或调用此方法出错时,都会调用回调。不要依赖 Promise rejection 来处理这种情况。

import { BackgroundGeolocation } from '@capgo/background-geolocation';
await BackgroundGeolocation.start(
{
backgroundMessage: "App is using your location in the background",
backgroundTitle: "Location Service",
requestPermissions: true,
stale: false,
distanceFilter: 10
},
(location, error) => {
if (error) {
console.error('Location error:', error);
return;
}
if (location) {
console.log('New location:', location.latitude, location.longitude);
}
}
);

停止位置更新。

import { BackgroundGeolocation } from '@capgo/background-geolocation';
await BackgroundGeolocation.stop();

打开设备的定位设置页面。 适用于引导用户开启定位服务或调整权限。

import { BackgroundGeolocation } from '@capgo/background-geolocation';
// Direct user to location settings
await BackgroundGeolocation.openSettings();

当用户偏离预定路线时播放音频文件。 应使用此功能播放声音(也支持后台播放,仅限原生端)。

import { BackgroundGeolocation } from '@capgo/background-geolocation';
await BackgroundGeolocation.setPlannedRoute({
soundFile: "notification.mp3",
route: [[-74.0060, 40.7128], [-118.2437, 34.0522]]
});

地理围栏在原生层运行,因此 iOS 和 Android 无需依赖 WebView 保持唤醒,也能触发进入和退出事件。当应用 UI 挂起时,如果你的后端仍需接收这些状态变更,请配置 HTTP 或 HTTPS webhook URL。

import { BackgroundGeolocation } from '@capgo/background-geolocation';
await BackgroundGeolocation.setupGeofencing({
url: 'https://api.example.com/geofences',
notifyOnEntry: true,
notifyOnExit: true,
payload: { userId: '123' },
});
await BackgroundGeolocation.addGeofence({
identifier: 'store-42',
latitude: 37.33182,
longitude: -122.03118,
radius: 150,
payload: { storeId: '42' },
});
const handle = await BackgroundGeolocation.addListener(
'geofenceTransition',
(event) => {
console.log(event.identifier, event.transition, event.time);
},
);
const errorHandle = await BackgroundGeolocation.addListener(
'geofenceError',
(event) => {
console.error(event.identifier, event.message);
},
);
const { regions } = await BackgroundGeolocation.getMonitoredGeofences();
console.log(regions);
await BackgroundGeolocation.removeGeofence({ identifier: 'store-42' });
await handle.remove();
await errorHandle.remove();

在 iOS 上,地理围栏需要“始终”定位授权。在 Android 10 及更高版本中,如果需要后台地理围栏,请在 app manifest 中添加后台定位权限:

<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

在 iOS 上,已终止的应用只有在从 app delegate 启动时才能收到穿越事件。 GeofenceRelay 当用户退出登录或你切换账户时,请暂停共享地理围栏以及账户专属的地理围栏:调用 removeAllGeofences(),或用以下方法移除每个剩余的共享地理围栏: removeGeofence()模式,然后调用 clearGeofenceQueue() 然后再设置另一个账户的凭据。 clearGeofenceQueue() 需要插件版本 8.6.0 或更高版本,因此 8.5.2 的应用必须先升级。如果 setup payload 包含账户专属数据,例如 userId,调用 setupGeofencing() 在添加该账户的地理围栏或恢复任何共享地理围栏之前,先用新账户的 payload 和凭据调用; updateHeaders() 单独使用并不会替换已持久化的 payload。请阅读 event.time 上的 webhook,因为排队的 POST 可能稍后到达。参见 地理围栏队列.

用于配置位置更新的选项。

export interface StartOptions {
/**
* If 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.
*
* @since 7.0.9
* @example "Getting your location to provide better service"
*/
backgroundMessage?: string;
/**
* The title of the notification mentioned above.
*
* @since 7.0.9
* @default "Using your location"
* @example "Location Service"
*/
backgroundTitle?: string;
/**
* Whether permissions should be requested from the user automatically,
* if they are not already granted.
*
* @since 7.0.9
* @default true
* @example
* // Auto-request permissions
* requestPermissions: true
*
* // Don't auto-request, handle manually
* requestPermissions: false
*/
requestPermissions?: boolean;
/**
* If "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.
*
* @since 7.0.9
* @default false
* @example
* // Allow stale locations for faster initial response
* stale: true
*
* // Only fresh locations
* stale: false
*/
stale?: boolean;
/**
* The 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.
*
* @since 7.0.9
* @default 0
* @example
* // Update every 10 meters
* distanceFilter: 10
*
* // Update on any movement
* distanceFilter: 0
*/
distanceFilter?: number;
}

表示具有多种属性的地理位置。包含 GPS/网络提供商返回的所有标准位置属性。

export interface Location {
/**
* Latitude in degrees.
* Range: -90.0 to +90.0
*
* @since 7.0.0
* @example 40.7128
*/
latitude: number;
/**
* Longitude in degrees.
* Range: -180.0 to +180.0
*
* @since 7.0.0
* @example -74.0060
*/
longitude: number;
/**
* Radius of horizontal uncertainty in metres, with 68% confidence.
* Lower values indicate more accurate location.
*
* @since 7.0.0
* @example 5.0
*/
accuracy: number;
/**
* Metres above sea level (or null if not available).
*
* @since 7.0.0
* @example 10.5
*/
altitude: number | null;
/**
* Vertical uncertainty in metres, with 68% confidence (or null if not available).
*
* @since 7.0.0
* @example 3.0
*/
altitudeAccuracy: number | null;
/**
* `true` if the location was simulated by software, rather than GPS.
* Useful for detecting mock locations in development or testing.
*
* @since 7.0.0
* @example false
*/
simulated: boolean;
/**
* Deviation from true north in degrees (or null if not available).
* Range: 0.0 to 360.0
*
* @since 7.0.0
* @example 45.5
*/
bearing: number | null;
/**
* Speed in metres per second (or null if not available).
*
* @since 7.0.0
* @example 2.5
*/
speed: number | null;
/**
* Time the location was produced, in milliseconds since the unix epoch.
* Use this to check if a location is stale when using stale: true.
*
* @since 7.0.0
* @example 1640995200000
*/
time: number | null;
}

可能传递给位置启动回调的错误对象。扩展了标准 Error,并包含可选的错误代码。

export interface CallbackError extends Error {
/**
* Optional error code for more specific error handling.
*
* @since 7.0.0
* @example "PERMISSION_DENIED"
*/
code?: string;
}
export interface SetPlannedRouteOptions {
/**
* The 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.
* @since 7.0.10
* @example "notification.mp3"
* */
soundFile: string;
/**
* 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.
* @since 7.0.11
* @example [[-74.0060, 40.7128], [-118.2437, 34.0522]]
*/
route: [number, number][];
/**
* The 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.
* @since 7.0.11
* @default 50
* @example 50
*/
distance: number;
}

本页面由插件的 src/definitions.ts生成。当上游的公共 API 发生变化时,请重新运行 sync。

如果你正在使用 快速入门 要规划原生插件工作,请将其与 使用 @capgo/background-geolocation 关于使用 @capgo/background-geolocation 时的原生能力, Capgo 插件目录 查看 Capgo 插件目录中的产品工作流, Capgo 提供的 Capacitor 插件 查看由 Capgo 提供的 Capacitor 插件中的实现细节, 添加或更新插件 关于“添加或更新插件”中的实现细节,以及 Ionic Enterprise 插件替代方案 关于“Ionic Enterprise 插件替代方案”中的产品工作流。