Langsung ke konten

Panduan Memulai

GitHub

@capgo/background-geolocation menggabungkan pelacakan lokasi background yang presisi dengan geofencing native untuk iOS dan Android. Gunakan untuk zona pengiriman, toko, lokasi kerja, kampus, check-in, peringatan rute, dan alur kerja apa pun yang butuh event enter atau exit bahkan saat WebView tidak berjalan.

Anda bisa menggunakan AI-Assisted Setup kami untuk menginstal plugin ini. Tambahkan skill Capgo ke tool AI Anda dengan command berikut:

Jendela terminal
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

Lalu gunakan prompt berikut:

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

Jika Anda lebih memilih Manual Setup, instal plugin dengan menjalankan perintah berikut dan ikuti petunjuk khusus platform di bawah ini:

Jendela terminal
bun add @capgo/background-geolocation
bunx cap sync
import { BackgroundGeolocation } from '@capgo/background-geolocation';

Minta izin lokasi background, mulai update dengan notifikasi Android yang terlihat oleh user, dan POST fix ke API Anda dari native code.

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

Setiap fix dikirim secara paralel ke JavaScript (selama WebView aktif) dan ke url dengan "source": "native" di dalam body JSON.

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

Di Android, deklarasikan ACCESS_BACKGROUND_LOCATION di manifest Anda saat membutuhkan POST geofence background (lihat bagian native geofencing di bawah).

await BackgroundGeolocation.addGeofence({
identifier: 'warehouse',
latitude: 32.7,
longitude: -117.1,
radius: 200,
});
await BackgroundGeolocation.stop();
  • Notifikasi Android: pembaruan latar belakang memerlukan backgroundMessage (dan judul) agar pengguna tahu mengapa lokasi aktif.
  • Fix usang: atur stale: false saat Anda hanya butuh fix GPS terbaru.
  • Izin: minta backgroundLocation secara terpisah pada versi Android modern.

Untuk mulai memantau perubahan lokasi perangkat, panggil method ini. Promise dikembalikan untuk menandakan bahwa pemanggilan telah selesai. Callback akan dipanggil setiap kali lokasi baru tersedia, atau jika terjadi error saat memanggil method ini. Jangan mengandalkan promise rejection untuk ini.

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

Hentikan update lokasi.

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

Membuka halaman pengaturan lokasi perangkat. Berguna untuk mengarahkan pengguna agar mengaktifkan layanan lokasi atau menyesuaikan izin.

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

Memutar file suara saat pengguna keluar dari rute yang direncanakan. Ini digunakan untuk memutar suara (juga di background, khusus untuk native).

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

Geofencing berjalan di layer native, sehingga iOS dan Android dapat memicu event enter dan exit tanpa bergantung pada WebView agar tetap aktif. Konfigurasikan URL webhook HTTP atau HTTPS saat backend Anda harus menerima transisi meskipun UI aplikasi sedang suspended.

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();

Di iOS, geofencing memerlukan otorisasi lokasi Always. Di Android 10 ke atas, tambahkan izin background location ke app manifest Anda saat membutuhkan background geofencing:

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

Opsi untuk konfigurasi pembaruan lokasi.

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

Merepresentasikan lokasi geografis dengan berbagai atribut. Berisi semua properti lokasi standar dari penyedia GPS/jaringan.

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

Objek error yang mungkin dikirim ke callback start location. Memperluas Error standar dengan kode error opsional.

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

Halaman ini dibuat dari plugin src/definitions.ts. Jalankan ulang sync saat API publik berubah di upstream.

Jika Anda menggunakan Panduan Memulai untuk merencanakan pekerjaan plugin native, hubungkan dengan Menggunakan @capgo/background-geolocation untuk kapabilitas native di Using @capgo/background-geolocation, Direktori Plugin Capgo untuk alur kerja produk di Direktori Plugin Capgo, Plugin Capacitor oleh Capgo untuk detail implementasi pada Capacitor Plugins oleh Capgo Menambahkan atau Memperbarui Plugin untuk detail implementasi di Menambahkan atau Memperbarui Plugin, dan Alternatif Plugin Ionic Enterprise untuk alur kerja produk dalam Alternatif Plugin Ionic Enterprise.