본문 바로가기

시작하기

GitHub

@capgo/background-geolocation iOS 및 Android를 위한 정밀한 백그라운드 위치 추적과 네이티브 geofencing 기능을 결합했습니다. 배달 구역, 매장, 작업 현장, 캠퍼스, 체크인, 경로 알림 등 WebView가 실행 중이지 않을 때도 진입 또는 이탈 이벤트가 필요한 모든 워크플로우에 활용하세요.

AI-Assisted Setup으로 플러그인을 설치할 수 있습니다. 다음 명령어로 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-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 본문에 포함됩니다.

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

Android에서는 다음을 선언합니다. ACCESS_BACKGROUND_LOCATION 배경 지오펜스 POST가 필요할 때 매니페스트에 추가하세요(아래 네이티브 지오펜싱 섹션 참조).

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]]
});

지오펜싱은 네이티브 레이어에서 실행되므로, WebView가 깨어 있지 않아도 iOS와 Android에서 진입 및 이탈 이벤트를 트리거할 수 있습니다. 앱 UI가 일시정지된 상태에서도 백엔드가 전환을 수신해야 한다면 HTTP 또는 HTTPS 웹훅 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 이상에서 백그라운드 지오펜싱이 필요하면 앱 매니페스트에 백그라운드 위치 권한을 추가하세요:

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

iOS에서 종료된 앱은 다음을 시작해야만 크로스 이벤트를 수신할 수 있습니다. GeofenceRelay 앱 델리게이트에서 시작하세요. 사용자가 로그아웃하거나 계정을 전환할 때, 공유 지오펜스뿐 아니라 계정별 지오펜스도 일시 중지해야 합니다. 다음을 호출하세요: removeAllGeofences(), 또는 다음을 사용하여 나머지 공유 지오펜스를 하나씩 제거하세요: removeGeofence(), 그런 다음 호출 clearGeofenceQueue() 다른 계정의 자격 증명을 설정하기 전에. clearGeofenceQueue() 는 플러그인 버전 8.6.0 이상이 필요하므로, 8.5.2를 사용하는 앱은 먼저 업그레이드해야 합니다. 설정 페이로드에 계정별 데이터(예: )가 포함된 경우, 해당 계정의 지오펜스를 추가하거나 공유 지오펜스를 복원하기 전에 새 계정의 페이로드와 자격 증명으로 userId, 호출 setupGeofencing() 를 호출하세요; updateHeaders() 만으로는 영속화된 페이로드를 대체하지 않습니다. 큐에 쌓인 POST가 나중에 도착할 수 있으므로 웹훅에서 event.time 를 읽어보세요. 참고: 지오펜스 큐.

타입 레퍼런스

“타입 참조” 섹션

위치 업데이트를 구성하기 위한 옵션입니다.

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.tsupstream에서 public API가 변경되면 sync를 다시 실행하세요.

사용 중이라면 시작하기 네이티브 플러그인 작업을 계획하려면, 이를 다음 항목과 연결하세요: @capgo/background-geolocation 사용하기 @capgo/background-geolocation 사용하기에서 네이티브 기능을 위해, Capgo 플러그인 디렉토리 Capgo Plugin Directory의 제품 워크플로우에 맞춰, Capgo의 Capacitor 플러그인 Capgo의 Capacitor 플러그인 구현 상세 내용에 대해서는, 플러그인 추가 또는 업데이트 플러그인 추가 또는 업데이트 구현 상세 내용에 대해서는, Ionic Enterprise 플러그인 대안 Ionic Enterprise 플러그인 대안의 제품 워크플로우에 대해서는.