Aller au contenu

Prise en main

GitHub

@capgo/background-geolocation combine un suivi de localisation en arrière-plan précis avec le géorepérage natif pour iOS et Android. Utilisez-le pour les zones de livraison, les magasins, les chantiers, les campus, les check-ins, les alertes de trajet et tout workflow nécessitant des événements d’entrée ou de sortie, même lorsque le WebView n’est pas actif.

Vous pouvez utiliser notre configuration assistée par IA pour installer le plugin. Ajoutez les skills Capgo à votre outil d'IA avec la commande suivante :

Fenêtre de terminal
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

Utilisez ensuite le prompt suivant :

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

Si vous préférez une installation manuelle, installez le plugin en exécutant les commandes suivantes et suivez les instructions spécifiques à chaque plateforme ci-dessous :

Fenêtre de terminal
bun add @capgo/background-geolocation
bunx cap sync
import { BackgroundGeolocation } from '@capgo/background-geolocation';

Demandez l’autorisation de localisation en arrière-plan, démarrez les mises à jour avec une notification Android visible par l’utilisateur et envoyez les positions à votre API depuis le code natif.

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

Chaque position est transmise en parallèl’à JavaScript (tant que la WebView est active) et à url par "source": "native" dans le corps JSON.

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

Sur Android, déclarez ACCESS_BACKGROUND_LOCATION dans votre manifeste lorsque vous avez besoin de POST de géofence en arrière-plan (voir la section sur la géofence native ci-dessous).

await BackgroundGeolocation.addGeofence({
identifier: 'warehouse',
latitude: 32.7,
longitude: -117.1,
radius: 200,
});
await BackgroundGeolocation.stop();
  • Notification Android: les mises à jour en arrière-plan nécessitent backgroundMessage (and title) so users see why location is active.
  • Positions obsolètes: définissez stale: false when you need GPS fresh fixes only.
  • Autorisations: demandez backgroundLocation séparément sur les versions récentes d'Android.

Pour commencer à écouter les changements de localisation de l'appareil, appelez cette méthode. Une Promise est renvoyée pour indiquer que l'appel est terminé. Le callback sera appelé chaque fois qu'une nouvelle localisation est disponible, ou en cas d'erreur lors de l'appel de cette méthode. Ne vous fiez pas au rejet de la Promise pour cela.

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

Arrête les mises à jour de localisation.

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

Ouvre la page des paramètres de localisation de l’appareil. Pratique pour guider les utilisateurs afin d’activer les services de localisation ou d’ajuster les autorisations.

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

Joue un fichier audio lorsque l’utilisateur s’écarte de l’itinéraire prévu. Cela doit être utilisé pour jouer un son (y compris en arrière-plan, uniquement pour le natif).

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

Le géorepérage s’exécute dans la couche native, ce qui permet à iOS et Android de déclencher des événements d’entrée et de sortie sans dépendre du maintien en veille du WebView. Configurez une URL de webhook HTTP ou HTTPS lorsque votre backend doit recevoir les transitions même si l’interface de l’application est suspendue.

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

Sur iOS, le géorepérage nécessite l’autorisation de localisation « Toujours ». Sur Android 10 et versions ultérieures, ajoutez l’autorisation de localisation en arrière-plan à votre manifeste d’application lorsque vous avez besoin de géorepérage en arrière-plan :

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

On iOS, a terminated app only receives crossings if you start GeofenceRelay depuis l'app delegate. Lorsque l'utilisateur se déconnecte ou que vous changez de compte, mettez en pause les géorepères partagés ainsi que ceux spécifiques au compte : appelez removeAllGeofences(), ou supprimez chaque géorepère partagé restant avec removeGeofence(), puis appelez clearGeofenceQueue() avant de définir les identifiants d'un autre compte. clearGeofenceQueue() requires plugin version 8.6.0 or later, so apps on 8.5.2 must upgrade first. If the setup payload includes account-specific data such as a userId, appelez setupGeofencing() avec la charge et les identifiants du nouveau compte avant d'ajouter les géorepères de ce compte ou de restaurer des géorepères partagés ; updateHeaders() seul ne remplace pas la charge persistée. Lisez event.time sur le webhook, car un POST en file d'attente peut arriver plus tard. Voir File d'attente geofence.

Les options de configuration des mises à jour de localisation.

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

Représente une position géographique avec divers attributs. Contient toutes les propriétés de localisation standard renvoyées par les fournisseurs GPS/réseau.

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

Objet d'erreur pouvant être transmis au callback de démarrage de la localisation. Étend l'objet Error standard avec des codes d'erreur facultatifs.

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

Cette page est générée à partir de src/definitions.ts. Relancez la synchronisation lorsque l’API public change en amont.

Si vous utilisez Prise en main pour planifier le travail sur les plugins natifs, connectez-l’à Utiliser @capgo/background-geolocation pour la capacité native dans Utiliser @capgo/background-geolocation, Capgo Répertoire des plugins pour le workflow produit dans Capgo Plugin Directory, Plugins Capacitor par Capgo pour les détails d'implémentation dans Plugins Capacitor par Capgo, Ajouter ou mettre à jour des plugins pour les détails d'implémentation dans Ajout ou mise à jour de plugins, et Alternatives aux plugins Ionic Enterprise pour le workflow produit dans Alternatives aux plugins Ionic Enterprise.