Vai al contenuto

Per iniziare

GitHub

@capgo/background-geolocation combina il tracciamento preciso della posizione in background con il geofencing nativo per iOS e Android. Usalo per zone di consegna, negozi, cantieri, campus, check-in, avvisi di percorso e qualsiasi workflow che richieda eventi di entrata o uscita anche quando la WebView non è in esecuzione.

Puoi usare il nostro setup assistito dall'IA per installare il plugin. Aggiungi le skill Capgo al tuo strumento di IA usando il seguente comando:

Finestra del terminale
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

Poi usa il seguente prompt:

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

Se preferisci la configurazione manuale, installa il plugin eseguendo questi comandi e segui le istruzioni specifiche per piattaforma qui sotto:

Finestra del terminale
bun add @capgo/background-geolocation
bunx cap sync
import { BackgroundGeolocation } from '@capgo/background-geolocation';

Richiedi il permesso di localizzazione in background, avvia gli aggiornamenti con un messaggio di notifica visibile su Android e invia i fix al tuo API dal code nativo.

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

Ogni fix viene consegnato in parallelo a JavaScript (mentre la WebView è attiva) e a url con "source": "native" nel corpo JSON.

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

Su Android, dichiara ACCESS_BACKGROUND_LOCATION nel tuo manifest quando ti servono POST di geofence in background (vedi la sezione geofencing nativa qui sotto).

await BackgroundGeolocation.addGeofence({
identifier: 'warehouse',
latitude: 32.7,
longitude: -117.1,
radius: 200,
});
await BackgroundGeolocation.stop();
  • Notifica Android: gli aggiornamenti in background richiedono backgroundMessage (e il titolo) così gli utenti capiscono perché la posizione è attiva.
  • Fix obsoleti: imposta stale: false quando servono solo fix GPS aggiornati.
  • Permessi: richiedi backgroundLocation separatamente sulle versioni moderne di Android.

Per iniziare ad ascoltare le variazioni della posizione del dispositivo, chiama questo metodo. Viene restituita una Promise per indicare che la chiamata è terminata. Il callback verrà chiamato ogni volta che è disponibile una nuova posizione, oppure se si è verificato un errore durante la chiamata a questo metodo. Non fare affidamento sul rejection della Promise per questo.

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

Interrompe gli aggiornamenti della posizione.

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

Apre la pagina delle impostazioni sulla posizione del dispositivo.\nUtile per indirizzare gli utenti ad abilitare i servizi di localizzazione o regolare i permessi.

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

Riproduce un file audio quando l'utente devia dal percorso pianificato. Da usare per riprodurre un suono (anche in background, solo su native).

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

Il geofencing gira nel layer nativo, quindi iOS e Android possono generare gli eventi enter ed exit senza dover mantenere attiva la WebView. Configura un URL webhook HTTP o HTTPS quando il tuo backend deve ricevere le transizioni anche mentre l'interfaccia dell'app è sospesa.

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

Su iOS, il geofencing richiede l'autorizzazione Always per la posizione. Su Android 10 e versioni successive, aggiungi il permesso di localizzazione in background al manifest della tua app quando ti serve il geofencing in background:

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

Su iOS, un'app terminata riceve solo gli eventi di crossing se li avvii GeofenceRelay dall'app delegate. Quando l'utente effettua il logout o cambi account, metti in pausa anche i geofence condivisi oltre a quelli specifici dell'account: chiama removeAllGeofences(), oppure rimuovi ogni geofence condiviso rimanente con removeGeofence(), quindi chiama clearGeofenceQueue() prima di impostare le credenziali di un altro account. clearGeofenceQueue() richiede la versione 8.6.0 o successiva del plugin, quindi le app su 8.5.2 devono prima essere aggiornate. Se il payload di configurazione include dati specifici dell'account come un userId, chiama setupGeofencing() con il payload e le credenziali del nuovo account prima di aggiungere i geofence di quell'account o di ripristinare i geofence condivisi; updateHeaders() da solo non sostituisce il payload persistito. Leggi event.time sul webhook perché un POST in coda potrebbe arrivare in ritardo. Vedi Coda geofence.

Le opzioni per configurare gli aggiornamenti di posizione.

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

Rappresenta una posizione geografica con vari attributi. Contiene tutte le proprietà standard della posizione restituite dai provider GPS/rete.

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

Oggetto errore che può essere passato al callback di avvio della posizione. Estende l'Error standard con codici di errore opzionali.

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

Questa pagina è generata dal src/definitions.ts. Riesegui la sync quando il API pubblico cambia upstream.

Se stai usando Per iniziare per pianificare il lavoro sui plugin nativi, collegalo a Usare @capgo/background-geolocation per la funzionalità nativa in Usare @capgo/background-geolocation, Directory dei plugin di Capgo per il workflow del prodotto nella Capgo Plugin Directory, Plugin Capacitor di Capgo per i dettagli di implementazione in Capacitor Plugins di Capgo, Aggiunta o aggiornamento dei plugin per i dettagli su come aggiungere o aggiornare i plugin, e Alternative ai plugin Ionic Enterprise per il workflow del prodotto in Alternative ai plugin Ionic Enterprise.