スタートガイド
インストール手順と、このプラグインの完全なMarkdownガイドを含むセットアッププロンプトをコピーします。
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/background-geolocation`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/docs/plugins/background-geolocation/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
@capgo/background-geolocation iOSとAndroid向けに、正確なバックグラウンド位置情報トラッキングとネイティブジオフェンシングを組み合わせます。配送ゾーン、店舗、現場、キャンパス、チェックイン、ルートアラートなど、WebViewが動作していないときでも進入・退出イベントが必要なあらゆるワークフローに利用できます。
インストール
「インストール」セクションAIアシストによるセットアップでプラグインをインストールできます。以下のコマンドを使用して、お使いのAIツールに Capgo のスキルを追加してください:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins次に、以下のプロンプトを使用します:
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/background-geolocation` plugin in my project.手動セットアップを希望する場合は、以下のコマンドを実行してプラグインをインストールし、下記のプラットフォーム別の手順に従ってください:
bun add @capgo/background-geolocationbunx 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); } },);各修正(fix)は、JavaScript(WebViewが動作している間)と、以下に並行して配信されます。 url を使用して "source": "native" JSONボディ内に。
例: geofence webhook
「例: geofence webhook」というタイトルのセクションawait BackgroundGeolocation.setupGeofencing({ url: 'https://api.example.com/geofence-hit', backgroundLocation: true,});Androidでは、以下を宣言してください。 ACCESS_BACKGROUND_LOCATION バックグラウンドでのgeofence POSTが必要な場合は、manifestに記述してください(後述のネイティブgeofencingセクションを参照)。
await BackgroundGeolocation.addGeofence({ identifier: 'warehouse', latitude: 32.7, longitude: -117.1, radius: 200,});例:トラッキングの停止
「例:トラッキングの停止」というセクションawait BackgroundGeolocation.stop();よくある落とし穴
「よくある落とし穴」セクション- Androidの通知: バックグラウンド更新には
backgroundMessage(およびタイトル)が必要です。これにより、ユーザーはなぜ位置情報が有効なのかを理解できます。 - 古い位置情報の修正: 設定
stale: falseGPSによる最新の修正のみが必要な場合。 - 権限: リクエスト
backgroundLocation最新のAndroidバージョンでは、個別にリクエストが必要です。
API の概要
「API 概要」セクションstart
「start」セクションデバイスの位置情報の変更を監視するには、このメソッドを呼び出します。 呼び出しの完了を示す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); } });stop
「stop」セクション位置情報の更新を停止します。
import { BackgroundGeolocation } from '@capgo/background-geolocation';
await BackgroundGeolocation.stop();openSettings
「openSettings」セクションデバイスの位置情報設定ページを開きます。 ユーザーに位置情報サービスを有効にしてもらったり、権限を調整してもらったりする場合に便利です。
import { BackgroundGeolocation } from '@capgo/background-geolocation';
// Direct user to location settingsawait BackgroundGeolocation.openSettings();setPlannedRoute
「setPlannedRoute」セクションユーザーが予定ルートから外れた際にサウンドファイルを再生します。 (ネイティブ環境のみ)バックグラウンドでもサウンドを再生する場合に使用してください。
import { BackgroundGeolocation } from '@capgo/background-geolocation';
await BackgroundGeolocation.setPlannedRoute({ soundFile: "notification.mp3", route: [[-74.0060, 40.7128], [-118.2437, 34.0522]]});Native geofencing
「Native geofencing」セクションGeofencingはネイティブレイヤーで動作するため、WebViewを起動させたままにすることなく、iOSやAndroidでenter/exitイベントをトリガーできます。アプリの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); },);
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では、geofencingに「常に許可(Always)」の位置情報権限が必要です。Android 10以降でバックグラウンドgeofencingが必要な場合は、アプリのmanifestにバックグラウンド位置情報の権限を追加してください:
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />型リファレンス
「型リファレンス」セクションStartOptions
“StartOptions” セクション位置情報の更新設定に関するオプションです。
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;}Location
“Location” セクションさまざまな属性を持つ地理的な位置を表します。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;}CallbackError
“CallbackError” セクションlocation start コールバックに渡される可能性のあるエラーオブジェクトです。標準の Error を拡張し、オプションのエラーコードを備えています。
export interface CallbackError extends Error { /** * Optional error code for more specific error handling. * * @since 7.0.0 * @example "PERMISSION_DENIED" */ code?: string;}SetPlannedRouteOptions
“SetPlannedRouteOptions” セクション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;}Source of Truth
「Source Of Truth」セクションこのページはプラグインの src/definitions.tsから生成されています。upstream で公開 API が変更されたら、再度 sync を実行してください。
Getting Startedの続きを進める
「Getting Started からの続き」セクション使用している場合 スタートガイド ネイティブプラグインの作業を計画するには、次と連携してください: @capgo/background-geolocation の使い方 @capgo/background-geolocation を使用して Native Build の機能を利用する場合: Capgo プラグインディレクトリ Capgo プラグインディレクトリのプロダクトワークフローについては、 Capgo による Capacitor プラグイン Capgo による Capacitor プラグインの実装詳細については、 プラグインの追加または更新 プラグインの追加または更新における実装詳細については、および Ionic Enterprise プラグインの代替案 Ionic Enterprise プラグインの代替案におけるプロダクトワークフローについては。