# Geofencing

> Register circular geofences and observe enter and exit crossings. The BeekonGeofence fields, the three methods, the geofenceEvents stream, per-geofence notifications, and what the SDK does near a fence in Beekon Cloud.

Source: https://docs.getbeekon.com/guide/geofencing/

Beekon watches circular geofences and tells you when the device crosses a boundary, `Enter` or `Exit`. Geofences are independent of tracking: they keep working across `start()` and `stop()`, survive process death and reboot, and fire whether or not a tracking session is running.

This page covers the geofences your app registers itself, in Local and Custom mode. In Beekon Cloud the server owns them: see [Geofences in Beekon Cloud](#geofences-in-beekon-cloud).

## BeekonGeofence

A geofence is a circle, two notify flags and an optional notification:

| Field           | Type       | Range                                                                                                        | Default |
| --------------- | ---------- | ------------------------------------------------------------------------------------------------------------ | ------- |
| `id`            | string     | `1 … 100` characters, must not start with the reserved prefix `bk:`; adding an existing `id` replaces it     | —       |
| `latitude`      | number (°) | `−90 … +90`, WGS-84                                                                                          | —       |
| `longitude`     | number (°) | `−180 … +180`, WGS-84                                                                                        | —       |
| `radiusMeters`  | number (m) | `> 0`; `≥ 100` recommended for reliable triggering                                                           | —       |
| `notifyOnEntry` | bool       | —                                                                                                            | `true`  |
| `notifyOnExit`  | bool       | —                                                                                                            | `true`  |
| `notification`  | object     | Optional OS notification shown on a crossing. See [Per-geofence notifications](#per-geofence-notifications). | `null`  |

The OS geofencing engines are reliable from about 100 m. A smaller radius triggers late or not at all, so use `≥ 100` even though any value `> 0` is accepted. On Android, a fence with both `notifyOnEntry` and `notifyOnExit` set to `false` is rejected.

## The three methods

Geofences are managed with add, remove and list. There is no `setGeofences`.

| Method                 | Behaviour                                                                                                                                             |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `addGeofences(list)`   | Register geofences. Adding an existing `id` replaces it. Atomic: if any entry fails validation, none are added and the call throws `InvalidGeofence`. |
| `removeGeofences(ids)` | Unregister by id. Unknown ids are ignored.                                                                                                            |
| `listGeofences()`      | The currently registered set.                                                                                                                         |

* Android

  ```kotlin
  Beekon.addGeofences(listOf(
    BeekonGeofence(
      id = "home", latitude = 12.9716, longitude = 77.5946, radiusMeters = 150.0,
    ),
  ))
  val current: List<BeekonGeofence> = Beekon.listGeofences()
  Beekon.removeGeofences(listOf("home"))
  // addGeofences throws BeekonException.InvalidGeofence on a bad entry
  ```

* iOS

  ```swift
  try await Beekon.shared.addGeofences([
    BeekonGeofence(
      id: "home", latitude: 12.9716, longitude: 77.5946, radiusMeters: 150
    ),
  ])
  let current = await Beekon.shared.listGeofences()
  try await Beekon.shared.removeGeofences(ids: ["home"])
  // addGeofences throws BeekonError.invalidGeofence on a bad entry;
  // both add and remove throw .geofencesManagedByServer in cloud mode
  ```

* Flutter

  ```dart
  await Beekon.instance.addGeofences([
    BeekonGeofence(
      id: 'home', latitude: 12.9716, longitude: 77.5946, radiusMeters: 150,
    ),
  ]);
  final current = await Beekon.instance.listGeofences();
  await Beekon.instance.removeGeofences(['home']);
  ```

* React Native

  ```ts
  await Beekon.addGeofences([
    { id: 'home', latitude: 12.9716, longitude: 77.5946, radiusMeters: 150 },
  ]);
  const current = await Beekon.listGeofences();
  await Beekon.removeGeofences(['home']);
  ```

## The geofenceEvents stream

Crossings arrive on the `geofenceEvents` stream as a `GeofenceEvent`:

| Field        | Meaning                                                                         |
| ------------ | ------------------------------------------------------------------------------- |
| `id`         | Unique event id, generated by the SDK. The server uses it to remove duplicates. |
| `geofenceId` | The `BeekonGeofence.id` that was crossed.                                       |
| `type`       | `Enter` or `Exit`.                                                              |
| `timestamp`  | When the crossing happened (UTC).                                               |

* Android

  ```kotlin
  Beekon.geofenceEvents.collect { e ->
    Log.d("beekon", "${e.type} ${e.geofenceId} @ ${e.timestamp}")
  }
  ```

* iOS

  ```swift
  for await e in await Beekon.shared.geofenceEvents {
    print("\(e.type) \(e.geofenceId) @ \(e.timestamp)")
  }
  ```

* Flutter

  ```dart
  Beekon.instance.geofenceEvents.listen((e) {
    print('${e.type} ${e.geofenceId} @ ${e.timestamp}');
  });
  ```

* React Native

  ```ts
  Beekon.onGeofenceEvent((e) => {
    console.log(e.type, e.geofenceId, e.timestamp);
  });
  ```

A crossing is also a location

A location recorded because of a crossing also appears on the `locations` stream, with `trigger == Geofence`. The `geofenceEvents` stream carries which fence and which direction; the `locations` stream carries the location. In the [upload payload](https://docs.getbeekon.com/guide/payload/#segmentsgeofence_events), both travel in the same batch, as `locations[]` and `geofence_events[]`. iOS’s `CLMonitor.Event` has no triggering location, so the uploaded geofence event carries no location on either platform.

## Per-geofence notifications

A geofence can carry a `notification` object. Beekon shows it as an OS notification when the device crosses the boundary. It works offline and when your app has been killed: the notification is shown from the device’s local copy of the fence, with no server, push or running tracking session.

The object is a `delivery` channel and up to two content blocks, one per direction:

| Field      | Type    | Required                                                           | Notes                                                                                                                                                                                                      |
| ---------- | ------- | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `delivery` | enum    | Android, iOS, Flutter: no, defaults to `local`. React Native: yes. | `local` shows it on the device at crossing time, offline. `cloud` is reserved for server push and not yet implemented. In self-managed mode, `delivery` must be `local`; `cloud` throws `InvalidGeofence`. |
| `onEnter`  | content | no                                                                 | Shown on entry. Requires `notifyOnEntry = true` (the default).                                                                                                                                             |
| `onExit`   | content | no                                                                 | Shown on exit. Requires `notifyOnExit = true` (the default).                                                                                                                                               |

Each content block:

| Field        | Type       | Required | Notes                                                                                                                                                                                                                   |
| ------------ | ---------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `title`      | string     | yes      | Notification title.                                                                                                                                                                                                     |
| `body`       | string     | yes      | Notification body.                                                                                                                                                                                                      |
| `importance` | enum       | no       | `high` (heads-up with sound, the default) or the quieter standard alert: Android `Default`, iOS `.default`, Flutter `NotificationImportance.standard` (`default` is a reserved word in Dart), React Native `'default'`. |
| `deepLink`   | string     | no       | URI placed in the notification payload for you to route on tap.                                                                                                                                                         |
| `data`       | string map | no       | Flat string key/value map carried in the payload.                                                                                                                                                                       |

A content block for a direction that is switched off can never be shown, so `addGeofences` rejects it: `onEnter` with `notifyOnEntry = false`, or `onExit` with `notifyOnExit = false`, throws `InvalidGeofence` (Android `BeekonException.InvalidGeofence`, iOS `BeekonError.invalidGeofence`, Flutter `InvalidGeofence`, React Native a `BeekonError` with kind `'invalidGeofence'`). A `notification` with neither block shows nothing.

Notifications need a permission

On Android 13 (API 33) and later the OS shows these notifications only with the `POST_NOTIFICATIONS` runtime permission, and iOS only with notification authorisation. Beekon never prompts by itself: ask with [`requestPermission(notifications)`](https://docs.getbeekon.com/start/permissions/#requesting-permissions) or your own code. On iOS the [permission doctor](https://docs.getbeekon.com/start/permissions/#the-permission-doctor) never lists `notifications`, so ask without waiting for it.

In [Beekon Cloud](https://docs.getbeekon.com/cloud/), the server owns the geofence set, so the `notification` is set on the fence through the [Geofences API](https://docs.getbeekon.com/api/geofences/), not in app code. It arrives with each fence on the sync-response slice and is shown on the device like a local one, offline and with the app killed.

* Android

  ```kotlin
  Beekon.addGeofences(listOf(
    BeekonGeofence(
      id = "home", latitude = 12.9716, longitude = 77.5946, radiusMeters = 150.0,
      notification = GeofenceNotification(
        delivery = NotificationDelivery.Local,
        onEnter = NotificationContent(
          title = "Welcome home",
          body = "You've arrived",
          importance = NotificationImportance.High,
          deepLink = "myapp://home",
          data = mapOf("zone" to "home"),
        ),
        onExit = NotificationContent(title = "Heading out", body = "See you soon"),
      ),
    ),
  ))
  ```

* iOS

  ```swift
  try await Beekon.shared.addGeofences([
    BeekonGeofence(
      id: "home", latitude: 12.9716, longitude: 77.5946, radiusMeters: 150,
      notification: GeofenceNotification(
        onEnter: NotificationContent(
          title: "Welcome home",
          body: "You've arrived",
          importance: .high,
          deepLink: "myapp://home",
          data: ["zone": "home"]
        ),
        onExit: NotificationContent(title: "Heading out", body: "See you soon"),
        delivery: .local
      )
    ),
  ])
  ```

* Flutter

  ```dart
  await Beekon.instance.addGeofences([
    BeekonGeofence(
      id: 'home', latitude: 12.9716, longitude: 77.5946, radiusMeters: 150,
      notification: GeofenceNotification(
        delivery: NotificationDelivery.local,
        onEnter: NotificationContent(
          title: 'Welcome home',
          body: "You've arrived",
          importance: NotificationImportance.high,
          deepLink: 'myapp://home',
          data: {'zone': 'home'},
        ),
        onExit: NotificationContent(title: 'Heading out', body: 'See you soon'),
      ),
    ),
  ]);
  ```

* React Native

  ```ts
  await Beekon.addGeofences([
    {
      id: 'home', latitude: 12.9716, longitude: 77.5946, radiusMeters: 150,
      notification: {
        delivery: 'local',
        onEnter: {
          title: 'Welcome home',
          body: "You've arrived",
          importance: 'high',
          deepLink: 'myapp://home',
          data: { zone: 'home' },
        },
        onExit: { title: 'Heading out', body: 'See you soon' },
      },
    },
  ]);
  ```

## Persistence & lifecycle

The native SDK saves registered geofences, so they outlive the process. A crossing can wake a terminated app and deliver an event before any tracking session exists. That is why geofencing is separate from the [lifecycle state machine](https://docs.getbeekon.com/guide/lifecycle/): `Beekon.state` describes the tracking session, while geofences run on the OS’s own monitoring whatever that state is.

Beekon uses the platform’s own engine: GMS `GeofencingClient` on Android, and `CLMonitor` (iOS 17+) or `CLCircularRegion` monitoring (iOS 15 and 16) on iOS. It registers the fences nearest the device and swaps them as it moves, so you can register more than the OS per-app limit. Android’s `DWELL` transition is not exposed.

## Geofences in Beekon Cloud

In [Beekon Cloud](https://docs.getbeekon.com/cloud/) the server owns the geofence set. You draw fences on the console’s [Geofences](https://docs.getbeekon.com/cloud/console/configure/#geofences) page or create them with the [Geofences API](https://docs.getbeekon.com/api/geofences/), as circles or polygons (a polygon reaches the device as multipolygon geometry). Each device receives the fences near it with its sync response, so a project can hold thousands.

* `addGeofences` and `removeGeofences` throw `GeofencesManagedByServer`.
* `listGeofences()` returns the fences the device received. A polygon appears there as its bounding circle, because `BeekonGeofence` is a circle. The device registers that circle with the OS and checks the polygon itself before it emits a crossing.
* The `geofence.*` events and webhooks come from the server, which checks the locations the device uploads: see [Events](https://docs.getbeekon.com/api/events/#geofence-events) and [Webhooks](https://docs.getbeekon.com/api/webhooks/).

No webhook for a crossing while tracking is stopped

The crossing your app sees on the device (the `geofenceEvents` stream and any local notification) and the webhook event are produced separately. The webhook comes from the server’s evaluation of the locations the device uploads. If the device crosses a fence while tracking is stopped, the app still gets the on-device event and the notification, but no crossing webhook is sent, because no locations were uploaded to evaluate. One exception: for a fence with [`on_unreachable: exit`](https://docs.getbeekon.com/api/geofences/#fence-policies), calling `stop()` while the device is inside makes the server send a `geofence.exit` with `evidence: unreachable`. It is dated when the server learned that tracking stopped, not when the device left.

## Near a fence (Beekon Cloud)

From SDK 0.6.0, a device in Cloud mode helps the server see each crossing sooner. There is no API and no setting for it: the SDK does it for the fences the server sends it.

* **It samples more often while moving near a fence, for a short time.** Within 150 m of a fence’s boundary (or twice the location’s accuracy, when that is more), a moving device records a location every 5 seconds or 10 metres instead of at the project’s usual interval. This lasts at most 120 seconds per approach, and never while tracking is paused, while the device is still, or with **Accuracy** set to **Low**. A fast drive-through of a small fence is then more likely to leave a location clearly inside it.
* **It uploads at once when it crosses a fence or comes close.** The SDK checks every location it records against the fences it holds. When a location is on the other side of a boundary from the one before, or is the first one near a fence, it uploads straight away instead of waiting for the [upload interval](https://docs.getbeekon.com/api/remote-config/#sync). This check emits nothing on the `geofenceEvents` stream.
* **An OS crossing asks for one fresh location.** While tracking, the SDK records one fresh location to judge the crossing and uploads it. On Android this happens for any OS crossing that comes without a location, including while tracking is paused because the device is still. On iOS it happens for a polygon fence’s crossing.
* **A phone at rest says so.** When the SDK pauses location updates because the device is still, it tells the server the device is resting, and moving again ends that. So the server does not mistake a phone on a desk for a lost one: a resting device can be silent until the project’s rest limit, while a moving device that goes silent is marked [unreachable](https://docs.getbeekon.com/api/events/#device-presence-events) after about twice its upload interval (on Android the interval counts as at least 15 minutes). The server reads the declaration while **When the device stops** is **Pause**; under the other settings it treats every tracking device as resting. On iOS the SDK pauses only with **Always** authorisation, so with **When In Use** it never declares rest.

The server still decides every geofence event, from the locations the device uploads: see [What produces a geofence event](https://docs.getbeekon.com/api/geofences/#what-produces-a-geofence-event). The extra locations near a fence use some battery, bounded by the 120-second limit per approach.

Requires SDK 0.6.0 or later. Devices on 0.5.0 and earlier upload near a fence only when the OS reports a crossing, and the server treats them as resting while they track.

Next: receive crossings on your backend, through the [upload payload](https://docs.getbeekon.com/guide/payload/#segmentsgeofence_events) on your own server or as [webhook events](https://docs.getbeekon.com/api/webhooks/) from Beekon Cloud.
