# Locations & history

> The Location type, raw passthrough, the live stream, the one-shot fix, and the on-device SQLite history with its schema, retention and read API.

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

There are three ways to read a location out of Beekon:

* **Live stream**: `locations`. Real time, no replay: a new subscriber gets only locations admitted after it subscribes. It emits only while the app process is alive.
* **One-shot fix**: `getCurrentLocation(timeout, accuracy)`. A single location now, independent of tracking.
* **History**: `getLocations(from, to)`. Reads the on-device SQLite database, which survives process death.

## The `Location` struct

A `Location` has the same 16 fields on all four platforms. On this page, a *fix* is the raw reading from the OS provider; a *location* is a fix that passed the [gate](https://docs.getbeekon.com/start/configuration/#the-gate) and was stored.

* `latitude`, `longitude` and `timestamp` are always present: the OS can’t return a fix without them.
* `accuracy`, `speed`, `bearing` and `altitude` are optional. `null` means the OS did not measure that field; `0` always means the OS reported zero.
* Every location also carries a stable `id`, derived metadata (`quality`, `trigger`, `motion`, `activity`, `isMock`) and the battery state when it was recorded (`batteryPercent`, `isCharging`, `powerSaveMode`).

```plaintext
id, latitude, longitude, timestamp,             // always present
accuracy?, speed?, bearing?, altitude?,         // null when unreported
quality, trigger, motion, activity, isMock,     // derived metadata
batteryPercent?, isCharging?, powerSaveMode?    // record-time battery,
                                                // null when unknown
```

| Field                   | Unit                                          | Notes                                                                                                                                    |
| ----------------------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                    | opaque                                        | stable identifier of the location                                                                                                        |
| `latitude`, `longitude` | degrees (WGS-84)                              | always present                                                                                                                           |
| `accuracy`              | metres (horizontal, 1σ)                       | `null` when the OS did not report                                                                                                        |
| `speed`                 | metres/second                                 | `null` when the OS did not report (e.g. stationary)                                                                                      |
| `bearing`               | degrees, `[0, 360)` clockwise from true north | `null` when unreported; direction of travel, not heading                                                                                 |
| `altitude`              | metres above WGS-84 ellipsoid                 | `null` when unreported or vertical accuracy invalid                                                                                      |
| `timestamp`             | wall-clock                                    | The OS provider’s fix time, not the time Beekon received it                                                                              |
| `quality`               | `LocationQuality`                             | the SDK’s own check of the fix; [values below](#quality-trigger-and-motion)                                                              |
| `trigger`               | `LocationTrigger`                             | why the location was captured; [values below](#quality-trigger-and-motion)                                                               |
| `motion`                | `MotionState`                                 | whether the device was moving; [values below](#quality-trigger-and-motion)                                                               |
| `activity`              | `ActivityType`, nullable                      | the detected activity; `null` unless `detectActivity` is on and granted. See [Activity detection](https://docs.getbeekon.com/guide/activity/)                      |
| `isMock`                | boolean                                       | whether the OS flagged the location as mock/simulated                                                                                    |
| `batteryPercent`        | integer `0…100`                               | battery level when the location was recorded (a cached OS sample, never polled); `null` when unknown (simulator, monitoring unavailable) |
| `isCharging`            | boolean                                       | charging (incl. full-on-charger) at record time; `null` when unknown                                                                     |
| `powerSaveMode`         | boolean                                       | Battery Saver / Low Power Mode active at record time; `null` when unknown                                                                |

### Quality, trigger and motion

Casing follows the platform: Android `LowAccuracy`, iOS `.lowAccuracy`, Flutter `LocationQuality.lowAccuracy`, React Native `'lowAccuracy'`. These enums may gain values in a minor release, so give every `switch` an `else` or `default` branch.

**`quality`** (`LocationQuality`). Every location is delivered, whatever its quality; this marks the suspect ones.

| Value              | Meaning                                                                                                         |
| ------------------ | --------------------------------------------------------------------------------------------------------------- |
| `ok`               | The fix passed the accuracy and speed checks.                                                                   |
| `lowAccuracy`      | Horizontal accuracy was worse than 100 m.                                                                       |
| `implausibleSpeed` | The speed implied by the distance from the previous stored location was above 300 m/s: a jump no vehicle makes. |

**`trigger`** (`LocationTrigger`).

| Value      | Meaning                                                                                   |
| ---------- | ----------------------------------------------------------------------------------------- |
| `interval` | A scheduled fix that passed the time and distance [gate](https://docs.getbeekon.com/start/configuration/#the-gate). |
| `motion`   | Captured because the device started or stopped moving.                                    |
| `checkIn`  | A check-in recorded while stationary, with `whenStationary` set to `pauseWithCheckIns`.   |
| `geofence` | Captured because the device crossed a geofence boundary.                                  |
| `manual`   | Returned by [`getCurrentLocation`](#one-shot-fix).                                        |

**`motion`** (`MotionState`).

| Value        | Meaning                                                                                                                                                    |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `moving`     | The device was moving.                                                                                                                                     |
| `stationary` | The device was stationary.                                                                                                                                 |
| `unknown`    | Not determined: early in a session, before motion detection has settled, or with `whenStationary` set to `keepTracking`, which turns motion detection off. |

The upload payload spells `quality` and `trigger` in snake case (`low_accuracy`, `check_in`); see [Payload](https://docs.getbeekon.com/guide/payload/).

## Raw passthrough

Beekon does not modify locations. There is no Kalman filter, outlier rejection, speed clamp or minimum-accuracy filter. What the OS provider produces is what you get on the stream and in history.

The one exception is in the `Location` constructor: invalid values (`NaN`, `Infinity`, a bearing outside `[0, 360)`) become `null`. Beekon drops values that can’t be meaningful; it never invents one. As a result, neighbouring locations can disagree a lot (between tall buildings, in a tunnel, at a cold start). Show that to users through `accuracy` rather than hiding it.

## The live stream

The live stream is hot and does not replay: each subscriber receives the locations admitted after it subscribed, so read `getLocations(...)` for anything earlier. On Android it is a `SharedFlow` with `replay = 0` and a 64-location buffer (`DROP_OLDEST`: a slow consumer drops old emissions but never blocks the producer). On iOS each access to `locations` returns its own `AsyncStream`, buffering the newest 64. `state` and `syncStatus` (and `authChanges`, once a token exists) replay their current value to each new subscriber; `locations`, `geofenceEvents` and `logs` don’t.

* Android

  ```kotlin
  Beekon.locations.collect { loc ->
    Log.d("beekon", "${loc.latitude}, ${loc.longitude}  acc=${loc.accuracy ?: "—"}m")
  }
  ```

* iOS

  ```swift
  Task {
    for await loc in await Beekon.shared.locations {
      let acc = loc.accuracy.map { String($0) } ?? "—"
      print("\(loc.latitude), \(loc.longitude)  acc=\(acc)m")
    }
  }
  ```

* Flutter

  ```dart
  Beekon.instance.locations.listen((loc) {
    print('${loc.latitude}, ${loc.longitude}  acc=${loc.accuracy ?? "—"}m');
  });
  ```

* React Native

  ```ts
  const off = Beekon.onLocation((loc) => {
    console.log(loc.latitude, loc.longitude, 'acc=', loc.accuracy ?? '—');
  });
  ```

The live stream emits only while the app process is alive. For locations recorded while the process was dead, read [history](#history).

### Filtering on top

A common case is dropping low-accuracy locations when drawing a map. Do it in your own stream consumer; history still records every location unfiltered.

* Android

  ```kotlin
  Beekon.locations
    .filter { (it.accuracy ?: Double.MAX_VALUE) <= 25.0 }
    .collect { /* render */ }
  ```

* iOS

  ```swift
  for await loc in await Beekon.shared.locations
    where (loc.accuracy ?? .infinity) <= 25 {
    // render
  }
  ```

* Flutter

  ```dart
  Beekon.instance.locations
    .where((loc) => (loc.accuracy ?? double.infinity) <= 25)
    .listen((loc) { /* render */ });
  ```

* React Native

  ```ts
  // filter in your onLocation callback
  ```

## One-shot fix

When you need a location at one moment (for example, when a trip starts) without starting tracking, call `getCurrentLocation` and `await` it. It works whether or not a session is running, and never starts, stops or changes one. The result goes to the caller only: it is not stored and does not appear on the live stream. It is tagged `trigger = Manual`.

It returns `null` only when no usable fix arrives within the timeout (default 15 s). A failed precondition throws instead, so you can tell “ask for permission” apart from “try again”. The reason is one of:

| Reason                     | Meaning                                                                                            |
| -------------------------- | -------------------------------------------------------------------------------------------------- |
| `PermissionDenied`         | Location permission is missing (on iOS, also denied or restricted).                                |
| `LocationServicesDisabled` | System location services are off. The user can turn them on.                                       |
| `Unavailable`              | Location can’t be read on this device. On Android, Google Play services is missing or out of date. |

Casing follows the platform: Android `LocationUnavailableReason.PermissionDenied`, iOS `.permissionDenied`, Flutter `LocationUnavailableReason.permissionDenied`. React Native rejects with a `BeekonError` whose `kind` is `'permissionDenied'`, `'locationServicesDisabled'` or `'locationUnavailable'`.

On iOS 15 and 16, `getCurrentLocation` ignores `timeout` and `accuracy`: it makes one standard Core Location request with about 10 m accuracy and gives up after 10 seconds. The parameters apply from iOS 17.

* Android

  ```kotlin
  val fix = Beekon.getCurrentLocation(
    timeoutMs = 15_000,
    accuracy = AccuracyMode.High,
  )
  if (fix != null) Log.d("beekon", "now at ${fix.latitude}, ${fix.longitude}")
  // null ⇒ timed out;
  // throws BeekonException.LocationUnavailable on a precondition failure
  ```

* iOS

  ```swift
  let fix = try await Beekon.shared.getCurrentLocation(
    timeout: 15, // seconds
    accuracy: .high
  )
  if let fix { print("now at \(fix.latitude), \(fix.longitude)") }
  // nil ⇒ timed out;
  // throws BeekonError.locationUnavailable(reason:) on a precondition failure
  ```

* Flutter

  ```dart
  final fix = await Beekon.instance.getCurrentLocation(
    timeout: const Duration(seconds: 15),
    accuracy: AccuracyMode.high,
  );
  // null ⇒ timed out; throws LocationUnavailable on a precondition failure
  ```

* React Native

  ```ts
  const fix = await Beekon.getCurrentLocation({ timeoutMs: 15000, accuracy: 'high' });
  // null ⇒ timed out; rejects with a BeekonError on a precondition failure
  ```

## History

Every location that passes the gate is written to a SQLite database owned by the native library. The schema, retention and write rules are the same on both platforms; only the engine differs (Room on Android, GRDB on iOS). The write happens in the native location callback, so it does not depend on the Dart or JS runtime being alive.

### Schema

Each row is one stored location. The table shows the core columns; the database has more (such as the id, motion, activity, quality, session, user id and battery fields).

| Column     | Type             | Meaning                                             |
| ---------- | ---------------- | --------------------------------------------------- |
| `ts`       | INTEGER NOT NULL | Unix milliseconds (timestamp from the OS provider)  |
| `lat`      | REAL NOT NULL    | Degrees                                             |
| `lng`      | REAL NOT NULL    | Degrees                                             |
| `accuracy` | REAL (nullable)  | Metres, horizontal 1σ; NULL when unreported         |
| `speed`    | REAL (nullable)  | Metres/second; NULL when unreported                 |
| `bearing`  | REAL (nullable)  | Degrees, `[0, 360)`; NULL when unreported           |
| `altitude` | REAL (nullable)  | Metres above WGS-84 ellipsoid; NULL when unreported |

The column names (`ts`, `lat`, `lng`) are internal storage names, not the public API. The `Location` type exposes `timestamp`, `latitude` and `longitude`. An index on `ts ASC` serves range queries.

| Platform | Path                                                                          |
| -------- | ----------------------------------------------------------------------------- |
| Android  | App-private data (Room default), in the app’s own process                     |
| iOS      | `Library/Application Support/beekon/beekon.db`, `isExcludedFromBackup = true` |

On iOS the database is excluded from iCloud backup.

### Retention

A prune runs every 200 inserts, with two limits:

```plaintext
Age: 7 days (only when sync is off)
Cap: 100,000 rows (always)
```

The cap keeps the newest 100,000 rows in every mode. The 7-day limit applies only in local-only mode. With [sync](https://docs.getbeekon.com/guide/sync/) on, the whole backlog is kept (up to the cap), so a device that was offline for a long time can upload it all when it reconnects.

### Reading history

`getLocations(from, to)` returns locations within both bounds (inclusive), sorted by `timestamp`, oldest first.

With sync on, history is the upload queue

A location stays in history until the server accepts its batch; then it is deleted on the device. So `getLocations` returns the locations not yet uploaded, not an archive of everything recorded. In `Local` mode (no sync), rows stay until retention removes them, so history is an archive bounded by the 7-day and 100,000-row limits.

* Android

  ```kotlin
  val now = Instant.now()
  val hourAgo = now.minus(1, ChronoUnit.HOURS)
  val history: List<Location> = Beekon.getLocations(from = hourAgo, to = now)
  // suspend; throws BeekonException.StorageException on DB failure
  ```

* iOS

  ```swift
  let now = Date()
  let hourAgo = now.addingTimeInterval(-3600)
  let history = try await Beekon.shared.getLocations(from: hourAgo, to: now)
  // async throws BeekonError.storage on DB failure
  ```

* Flutter

  ```dart
  final now = DateTime.now();
  final hourAgo = now.subtract(const Duration(hours: 1));
  final history = await Beekon.instance.getLocations(from: hourAgo, to: now);
  ```

* React Native

  ```ts
  const now = new Date();
  const hourAgo = new Date(Date.now() - 3_600_000);
  const history = await Beekon.getLocations(hourAgo, now);
  ```

No pagination

The history API returns the whole range in one call. There is no cursor. For very long ranges or a memory-constrained screen, split the range yourself (for example, one day per call).

Reads and writes share one database in WAL mode, so readers don’t block the writer. Reading history while tracking does not delay new locations.

### Deleting history

`deleteLocations(before)` deletes stored locations and returns how many it deleted. Pass a cutoff to delete every location captured strictly before that instant; a location captured exactly at the cutoff is kept. Pass nothing (or `nil`) to delete them all, which is the on-device half of a “delete my data” request.

* Android

  ```kotlin
  val removed: Int = Beekon.deleteLocations(
    before = Instant.now().minus(30, ChronoUnit.DAYS),
  )
  Beekon.deleteLocations() // delete all (before defaults to null)
  // suspend; throws BeekonException.StorageException on DB failure
  ```

* iOS

  ```swift
  let removed = try await Beekon.shared.deleteLocations(
    before: Date().addingTimeInterval(-30 * 86_400)
  )
  _ = try await Beekon.shared.deleteLocations(before: nil) // delete all
  ```

* Flutter

  ```dart
  final removed = await Beekon.instance.deleteLocations(
    before: DateTime.now().subtract(const Duration(days: 30)),
  );
  await Beekon.instance.deleteLocations(); // delete all
  ```

* React Native

  ```ts
  const removed = await Beekon.deleteLocations(
    new Date(Date.now() - 30 * 86_400_000),
  );
  await Beekon.deleteLocations(); // delete all
  ```

Retention already removes old locations, so use `deleteLocations()` for erasure on request, not routine cleanup. With sync on, deleting a location that hasn’t been uploaded loses it for good: it never reaches your server.

To label each location with the device’s physical activity, see [Activity detection](https://docs.getbeekon.com/guide/activity/).
