capacitor-local-geofence
v0.1.0-beta.1
Published
Server-free geofencing for Capacitor: enter/exit events persisted on device with timestamps and native local notifications, even when the app is closed.
Maintainers
Readme
capacitor-local-geofence
Server-free geofencing for Capacitor: enter/exit events persisted on device with timestamps and native local notifications, even when the app is closed.
Install
To use npm
npm install capacitor-local-geofenceTo use yarn
yarn add capacitor-local-geofenceSync native files
npx cap syncWhy
Most geofencing plugins either need a paid licence or deliver background events only to a web server. This plugin keeps everything on the device:
- Enter/exit events are persisted natively with a timestamp, also when the app is closed or was killed.
- An optional native local notification is shown per transition (
{time}placeholder for the local time). - The app reads the stored events with
getEvents()the next time it runs, or live via thetransitionlistener. - Regions survive app restarts, device reboots and app updates.
No server, no account, no licence key.
Platform setup
iOS
Add to ios/App/App/Info.plist:
<key>NSLocationWhenInUseUsageDescription</key>
<string>Used to detect when you arrive at or leave your saved places.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Used to detect when you arrive at or leave your saved places, also while the app is closed.</string>No background mode is required: region monitoring relaunches the app in the background for each transition.
iOS monitors at most 20 regions per app. Radii above the device's maximumRegionMonitoringDistance are rejected.
Events while the app is closed need Background App Refresh enabled for the app, the "Always" permission and
precise location (with approximate location location reports denied and addRegion rejects).
Recreate the region monitor at launch so events that relaunch a closed app are not missed before the
Capacitor bridge has loaded. In ios/App/App/AppDelegate.swift:
import LocalGeofencePlugin // CocoaPods projects: import CapacitorLocalGeofence
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
_ = LocalGeofence.shared
return true
}The plugin ships a privacy manifest (PrivacyInfo.xcprivacy) declaring its UserDefaults use (reason CA92.1).
Android
Add to android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />The plugin declares RECEIVE_BOOT_COMPLETED and its receivers itself. It uses Google Play services
(com.google.android.gms:play-services-location, override the version with playServicesLocationVersion
in android/variables.gradle). Devices without Play services cannot geofence.
Fine location is required; coarse-only location reports location: 'denied'.
Usage
import { LocalGeofence } from 'capacitor-local-geofence';
// Foreground location first, then the background upgrade (Android 11+ and iOS require this order).
await LocalGeofence.requestPermissions({ permissions: ['location', 'notifications'] });
await LocalGeofence.requestPermissions({ permissions: ['backgroundLocation'] });
await LocalGeofence.addRegion({
id: 'office',
latitude: 52.52,
longitude: 13.405,
radius: 150,
exitNotification: { title: 'Left the office', body: 'Stop the timer at {time}?' },
});
// On app start / resume: process what happened while the app was closed.
const { events } = await LocalGeofence.getEvents();
for (const event of events) {
console.log(event.regionId, event.transition, new Date(event.timestamp));
}
await LocalGeofence.clearEvents({ ids: events.map((e) => e.id) });Behaviour notes
- Adding a region while already inside it records no event on Android; iOS may deliver an immediate
enter. - A repeated identical transition for the same region (e.g. two
exitin a row) is dropped. - Geofence accuracy depends on the OS: expect 100–200 m jitter and delays of a few minutes, especially on Android.
- Android timestamps come from the triggering location, iOS timestamps from the moment of delivery.
- At most the newest 500 events are kept.
- Notifications are meant for the background. While the app is in the foreground iOS shows them only if
another plugin (e.g.
@capacitor/local-notificationswithpresentationOptions) presents notifications; use thetransitionlistener in the foreground instead. - Android: an ordinary process kill keeps monitoring, but force stop (Settings → Force stop) removes all geofences; monitoring resumes only when the user opens the app again, and transitions in between are lost. On iOS, force-quitting from the app switcher behaves similarly on some versions.
- Android re-adds regions after reboot, app update, location being turned back on (not delivered on every Android version), with background retries after a geofencing outage, and on every app resume.
API
checkPermissions()requestPermissions(...)addRegion(...)removeRegion(...)getRegions()getEvents()clearEvents(...)addListener('transition', ...)removeAllListeners()- Interfaces
- Type Aliases
checkPermissions()
checkPermissions() => Promise<PermissionStatus>Returns: Promise<PermissionStatus>
Since: 0.1.0
requestPermissions(...)
requestPermissions(options?: RequestPermissionsOptions | undefined) => Promise<PermissionStatus>| Param | Type |
| ------------- | ------------------------------------------------------------------------------- |
| options | RequestPermissionsOptions |
Returns: Promise<PermissionStatus>
Since: 0.1.0
addRegion(...)
addRegion(options: Region) => Promise<void>Start monitoring a circular region. Regions persist across app restarts and device reboots. iOS monitors at most 20 regions per app.
| Param | Type |
| ------------- | ----------------------------------------- |
| options | Region |
Since: 0.1.0
removeRegion(...)
removeRegion(options: { id: string; }) => Promise<void>| Param | Type |
| ------------- | ---------------------------- |
| options | { id: string; } |
Since: 0.1.0
getRegions()
getRegions() => Promise<{ regions: Region[]; }>Returns: Promise<{ regions: Region[]; }>
Since: 0.1.0
getEvents()
getEvents() => Promise<{ events: TransitionEvent[]; }>All recorded transitions, oldest first, including those that happened while the app was closed.
Events stay stored until clearEvents is called (at most the newest 500).
Returns: Promise<{ events: TransitionEvent[]; }>
Since: 0.1.0
clearEvents(...)
clearEvents(options?: { ids?: string[] | undefined; } | undefined) => Promise<void>Delete recorded events. Without ids all events are deleted.
| Param | Type |
| ------------- | -------------------------------- |
| options | { ids?: string[]; } |
Since: 0.1.0
addListener('transition', ...)
addListener(eventName: 'transition', listenerFunc: (event: TransitionEvent) => void) => Promise<PluginListenerHandle>Called for each transition while the app is running. The event is stored as well,
so getEvents still returns it.
| Param | Type |
| ------------------ | ------------------------------------------------------------------------------- |
| eventName | 'transition' |
| listenerFunc | (event: TransitionEvent) => void |
Returns: Promise<PluginListenerHandle>
Since: 0.1.0
removeAllListeners()
removeAllListeners() => Promise<void>Since: 0.1.0
Interfaces
PermissionStatus
| Prop | Type | Description | Since |
| ------------------------ | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
| location | PermissionState | Location while the app is in use (Android: fine/coarse location, iOS: "when in use" or "always"). | 0.1.0 |
| backgroundLocation | PermissionState | Location while the app is closed (Android: ACCESS_BACKGROUND_LOCATION, iOS: "always"). Required for geofence events while the app is not running. | 0.1.0 |
| notifications | PermissionState | Permission to show the native transition notifications. | 0.1.0 |
RequestPermissionsOptions
| Prop | Type | Description | Default | Since |
| ----------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | ----- |
| permissions | LocalGeofencePermissionType[] | Permissions to request. Request location before backgroundLocation: Android 11+ and iOS only grant background location as an upgrade of foreground location. | ['location', 'notifications'] | 0.1.0 |
Region
| Prop | Type | Description | Default | Since |
| ----------------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ----------------- | ----- |
| id | string | Unique identifier. Adding a region with an existing id replaces it. | | 0.1.0 |
| latitude | number | | | 0.1.0 |
| longitude | number | | | 0.1.0 |
| radius | number | Radius in meters. Values below ~100 m trigger unreliably on both platforms. | | 0.1.0 |
| notifyOnEnter | boolean | Record enter transitions. | true | 0.1.0 |
| notifyOnExit | boolean | Record exit transitions. | true | 0.1.0 |
| enterNotification | TransitionNotification | Native notification shown on enter. Omit to record the event silently. | | 0.1.0 |
| exitNotification | TransitionNotification | Native notification shown on exit. Omit to record the event silently. | | 0.1.0 |
| androidSmallIcon | string | Android only: drawable resource name for the notification small icon (e.g. ic_stat_geofence). Falls back to the app icon. | | 0.1.0 |
TransitionNotification
| Prop | Type | Description | Since |
| ----------- | ------------------- | ---------------------------------------------------------------------------------------------- | ----- |
| title | string | Notification title. {time} is replaced with the local time of the transition (e.g. 17:42). | 0.1.0 |
| body | string | Notification body. {time} is replaced with the local time of the transition. | 0.1.0 |
TransitionEvent
| Prop | Type | Description | Since |
| ---------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ----- |
| id | string | Unique event id, use it with clearEvents. | 0.1.0 |
| regionId | string | | 0.1.0 |
| transition | Transition | | 0.1.0 |
| timestamp | number | Time of the transition in milliseconds since epoch (Android: time of the triggering location, iOS: time of delivery). | 0.1.0 |
PluginListenerHandle
| Prop | Type |
| ------------ | ----------------------------------------- |
| remove | () => Promise<void> |
Type Aliases
PermissionState
'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'
LocalGeofencePermissionType
'location' | 'backgroundLocation' | 'notifications'
Transition
'enter' | 'exit'
