시작하기
이 플러그인은 Capacitor v7을 지원합니다:
| Capacitor | Plugin |
|---|---|
| v7 | v7 |
npm install @capgo/background-geolocationnpx cap updateyarn add @capgo/background-geolocationnpx cap updatepnpm add @capgo/background-geolocationnpx cap updatebun add @capgo/background-geolocationnpx cap update플랫폼 설정
Section titled “플랫폼 설정”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
Section titled “Android”Capacitor 구성에서 android.useLegacyBridge 옵션을 true로 설정하세요. 이렇게 하면 백그라운드에서 5분 후 위치 업데이트가 중단되는 것을 방지할 수 있습니다. https://capacitorjs.com/docs/config 및 https://github.com/capacitor-community/background-geolocation/issues/89를 참조하세요.
Android 13+에서는 앱이 사용자에게 백그라운드에서 위치를 사용 중임을 알리는 지속 알림을 표시하기 위해 POST_NOTIFICATIONS 런타임 권한이 필요합니다. 이 런타임 권한은 위치 권한이 부여된 후에 요청됩니다.
앱이 실시간으로 서버에 위치 업데이트를 전달하는 경우, 백그라운드에서 5분 후 Android가 WebView에서 시작된 HTTP 요청을 제한한다는 점에 유의하세요. 해결책은 CapacitorHttp와 같은 네이티브 HTTP 플러그인을 사용하는 것입니다. https://github.com/capacitor-community/background-geolocation/issues/14를 참조하세요.
Android 관련 구성은 strings.xml에서 할 수 있습니다:
<resources> <!-- 백그라운드 알림의 채널 이름입니다. 사용자가 알림을 길게 누르면 표시됩니다. 기본값은 "Background Tracking"입니다. --> <string name="capacitor_background_geolocation_notification_channel_name"> Background Tracking </string>
<!-- 백그라운드 알림에 사용할 아이콘입니다. "@"를 제외하세요. 기본값은 앱의 실행 아이콘인 "mipmap/ic_launcher"입니다.
벡터 이미지가 아닌 래스터 이미지를 사용하여 아이콘을 생성하는 경우 투명한 배경이 있어야 합니다. 이미지가 호환되는지 확인하려면 Android Studio에서 이미지 자산을 생성할 때 아이콘 유형으로 "Notification Icons"를 선택하세요.
호환되지 않는 이미지 자산은 아이콘이 올바르게 표시되더라도 알림이 몇 가지 명백한 방식으로 오작동하게 합니다:
- 알림이 사용자가 닫을 수 없어야 하는데 닫을 수 있습니다. - 알림을 탭하면 앱이 아닌 설정이 열립니다. - 알림 텍스트가 잘못될 수 있습니다. --> <string name="capacitor_background_geolocation_notification_icon"> drawable/ic_tracking </string>
<!-- android.graphics.Color.parseColor로 파싱할 수 있는 문자열로 알림의 색상입니다. 선택 사항입니다. --> <string name="capacitor_background_geolocation_notification_color"> yellow </string></resources>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 });
// 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); });}start(…)
Section titled “start(…)”start(options: StartOptions, callback: (position?: Location | undefined, error?: CallbackError | undefined) => void) => Promise<void>기기의 위치 변경 사항을 수신하려면 이 메서드를 호출하세요. 호출이 완료되었음을 나타내기 위해 Promise가 반환됩니다. 새로운 위치를 사용할 수 있거나 이 메서드를 호출할 때 오류가 발생하면 콜백이 호출됩니다. 이를 위해 promise rejection에 의존하지 마세요.
| Param | Type | Description |
|---|---|---|
options | StartOptions | 구성 옵션 |
callback | (position?: Location, error?: CallbackError) => void | 새 위치를 사용할 수 있거나 오류가 발생할 때 호출되는 콜백 함수 |
stop()
Section titled “stop()”stop() => Promise<void>위치 업데이트를 중지합니다.
openSettings()
Section titled “openSettings()”openSettings() => Promise<void>기기의 위치 설정 페이지를 엽니다. 사용자가 위치 서비스를 활성화하거나 권한을 조정하도록 안내하는 데 유용합니다.
setPlannedRoute(…)
Section titled “setPlannedRoute(…)”setPlannedRoute(options: SetPlannedRouteOptions) => Promise<void>사용자가 계획된 경로에서 벗어나면 사운드 파일을 재생합니다. 이것은 사운드를 재생하는 데 사용되어야 합니다 (백그라운드에서도, 네이티브만 해당).
| Param | Type | Description |
|---|---|---|
options | SetPlannedRouteOptions | 계획된 경로 및 사운드 파일 설정 옵션 |
StartOptions
Section titled “StartOptions”위치 업데이트 구성 옵션입니다.
| Prop | Type | Description | Default |
|---|---|---|---|
backgroundMessage | string | ”backgroundMessage” 옵션이 정의되면 플러그인은 앱이 백그라운드에 있든 포그라운드에 있든 위치 업데이트를 제공합니다. 정의되지 않으면 위치 업데이트는 포그라운드에서만 보장됩니다. 이는 두 플랫폼 모두에서 true입니다. Android에서는 백그라운드에서 위치 업데이트를 계속 받으려면 알림을 표시해야 합니다. 이 옵션은 해당 알림의 텍스트를 지정합니다. | |
backgroundTitle | string | 위에서 언급한 알림의 제목입니다. | "Using your location" |
requestPermissions | boolean | 권한이 아직 부여되지 않은 경우 사용자로부터 자동으로 권한을 요청할지 여부입니다. | true |
stale | boolean | ”true”이면 기기가 GPS 수정을 얻는 동안 오래된 위치가 전달될 수 있습니다. “time” 속성을 확인할 책임이 있습니다. “false”이면 위치가 최신 상태임이 보장됩니다. | false |
distanceFilter | number | 새로운 위치 업데이트가 트리거되기 전에 기기가 이동해야 하는 거리(미터)입니다. 이는 작은 이동을 필터링하고 업데이트 수를 줄이는 데 사용됩니다. | 0 |
Location
Section titled “Location”다양한 속성을 가진 지리적 위치를 나타냅니다. GPS/네트워크 제공자가 반환하는 모든 표준 위치 속성을 포함합니다.
| Prop | Type | Description |
|---|---|---|
latitude | number | 도 단위의 위도입니다. 범위: -90.0 ~ +90.0 |
longitude | number | 도 단위의 경도입니다. 범위: -180.0 ~ +180.0 |
accuracy | number | 68% 신뢰도로 수평 불확실성 반경(미터)입니다. 값이 낮을수록 위치가 더 정확합니다. |
altitude | number | null | 해발 미터(사용할 수 없는 경우 null). |
altitudeAccuracy | number | null | 68% 신뢰도로 수직 불확실성(미터)(사용할 수 없는 경우 null). |
simulated | boolean | GPS가 아닌 소프트웨어에 의해 위치가 시뮬레이션된 경우 true입니다. 개발 또는 테스트에서 모의 위치를 감지하는 데 유용합니다. |
bearing | number | null | 진북으로부터의 편차(도)(사용할 수 없는 경우 null). 범위: 0.0 ~ 360.0 |
speed | number | null | 초당 미터 단위의 속도(사용할 수 없는 경우 null). |
time | number | null | 위치가 생성된 시간(유닉스 에포크 이후 밀리초). stale: true를 사용할 때 위치가 오래되었는지 확인하는 데 사용하세요. |
CallbackError
Section titled “CallbackError”위치 시작 콜백에 전달될 수 있는 오류 객체입니다. 선택적 오류 코드로 표준 Error를 확장합니다.
| Prop | Type | Description |
|---|---|---|
code | string | 더 구체적인 오류 처리를 위한 선택적 오류 코드입니다. |
SetPlannedRouteOptions
Section titled “SetPlannedRouteOptions”| Prop | Type | Description | Default |
|---|---|---|---|
soundFile | string | 재생할 사운드 파일의 이름입니다. 웹 및 네이티브 플랫폼 모두에서 작동하려면 앱의 public 폴더에서 유효한 사운드 상대 경로여야 합니다. 경로에 public 폴더를 포함할 필요가 없습니다. | |
route | [number, number][] | 경도 및 위도 쌍의 배열로 계획된 경로입니다. 각 쌍은 경로의 한 지점을 나타냅니다. 이것은 사용자가 따를 수 있는 경로를 정의하는 데 사용됩니다. 경로는 사용자가 벗어날 때 사운드를 재생하는 데 사용됩니다. | |
distance | number | 사용자가 사운드를 트리거하기 위해 계획된 경로에서 벗어나야 하는 거리(미터)입니다. 이것은 사용자가 사운드가 재생되기 전에 경로에서 얼마나 멀리 떨어질 수 있는지 결정하는 데 사용됩니다. 지정하지 않으면 기본값 50미터가 사용됩니다. | 50 |