> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# LynxGeolocation

Finds where the phone is, once or as it moves, even with your app in the background, and hears when it enters or leaves an area. Lynx has no `navigator.geolocation`, so this is its stand-in, shaped like it. `import { LynxGeolocation } from '@blotch/angular-lynx';`

- **iOS:** Core Location. iOS asks the person the first time, and lets them turn off Precise Location, which reads as `approximate`.
- **Android:** `LocationManager`, without Google Play services. Android 12 and later let the person choose approximate or precise in the prompt.

## Turn it on

Add `permissions.location` to the `build` target's options in angular.json, with the [reason](/guide/native-apps/permissions.md) iOS shows when it asks:

```json title="angular.json"
"options": {
  "permissions": { "location": "Shows the shops near you" }
}
```

What it adds:

- **iOS:** `NSLocationWhenInUseUsageDescription`, the reason iOS's prompt shows.
- **Android:** `ACCESS_COARSE_LOCATION` and `ACCESS_FINE_LOCATION`, which Android asks for at runtime. Location hardware is declared not required, so Google Play still offers the app to devices without it.

Without it, the native code behind `LynxGeolocation` is left out of both apps. App Store Connect would flag an app whose code uses Core Location without saying why. `state()` is then `unsupported`, and every call rejects with `unavailable`.

Two more settings go further. Each needs `permissions.location` too:

```json title="angular.json"
"options": {
  "backgroundLocation": true,
  "permissions": {
    "location": "Follows your run on the map",
    "locationAlways": "Tells you when you reach the shop"
  }
}
```

| Setting                      | Lets the app                                                                                                      | Adds                                                                                                                                                                                 |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `backgroundLocation`         | Keep a watch going with the app in the background and the phone locked (`watchPosition({ background: true })`)    | **iOS:** the `location` background mode (`UIBackgroundModes`). **Android:** a foreground service of the `location` type, with `FOREGROUND_SERVICE` and `FOREGROUND_SERVICE_LOCATION` |
| `permissions.locationAlways` | Ask for the location all the time (`requestPermission({ always: true })`), and hear about areas (`watchRegion()`) | **iOS:** `NSLocationAlwaysAndWhenInUseUsageDescription`, the reason its Always prompt shows. **Android:** `ACCESS_BACKGROUND_LOCATION`                                               |

**A run tracker needs only `backgroundLocation`.** A watch the app starts on the screen carries on in the background with the usual "while using the app" permission. Google Play reviews every app that declares `ACCESS_BACKGROUND_LOCATION`, and asks for a video of the app's disclosure, so leave `locationAlways` out unless the app watches areas.

App Review rejects an app with the `location` background mode that has no use for it (guideline 2.5.4). Without the settings, the app has none of their code.

See [Turn on device features](/guide/native-apps/device-features.md) for every setting.

## Usage

```typescript
import { Component, inject, signal } from '@angular/core';
import {
  LYNX_ELEMENTS,
  LynxGeolocation,
  type GeolocationError,
  type GeolocationPosition,
} from '@blotch/angular-lynx';
import { Shops, type Shop } from './shops';

@Component({
  selector: 'app-nearby',
  imports: [LYNX_ELEMENTS],
  template: `
    <view (bindtap)="find()"><text>Find shops near me</text></view>
    @if (problem() === 'denied') {
      <text>Allow location to see shops near you.</text>
    }
    @for (shop of shops(); track shop.id) {
      <text>{{ shop.name }}</text>
    }
  `,
})
export class Nearby {
  readonly #geolocation = inject(LynxGeolocation);
  readonly #shops = inject(Shops);
  readonly shops = signal<Shop[]>([]);
  readonly problem = signal<string | undefined>(undefined);

  async find() {
    try {
      // Asks the person first, if they haven't been asked.
      const here = await this.#geolocation.getCurrentPosition({
        accuracy: 'approximate',
      });
      this.shops.set(await this.#shops.near(here.latitude, here.longitude));
    } catch (error) {
      this.problem.set((error as GeolocationError).code);
    }
  }
}
```

`Shops` stands for the app's own service.

To follow the phone as it moves, start a watch. Started in a constructor, it stops when the component is destroyed:

```typescript
readonly route = signal<GeolocationPosition[]>([]);

constructor() {
  inject(LynxGeolocation)
    .watchPosition({ distanceFilter: 20 }, (position) =>
      this.route.update((route) => [...route, position]),
    )
    .catch((error: GeolocationError) => this.problem.set(error.code));
}
```

**Ask when the person can see why**, such as when they tap "Find shops near me", rather than as the app launches. The system soon stops asking:

- iOS asks once.
- Android 11 and later stop asking after a second refusal.
- Earlier Android versions stop once the person ticks "Don't ask again".

A person the system no longer asks has to allow it in Settings, where [`openAppSettings()`](/api/angular-lynx/sharing/linking.md#lynxlinkingopenappsettings) takes them. `getCurrentPosition()` and `watchPosition()` ask by themselves. Call `requestPermission()` to ask at a moment of your choosing.

**A watch runs while the app is in use,** unless it's a background watch. iOS stops a watch while the app is in the background, and Android slows it to a few positions an hour. Stop a watch the app doesn't need there ([`LynxAppState`](/api/angular-lynx/device/app-state.md) says when).

### Follow the phone in the background

With `backgroundLocation` on, a watch started with `background` goes on with the app in the background and the phone locked, as a run or a delivery is followed:

```typescript
readonly #geolocation = inject(LynxGeolocation);
#watch?: GeolocationWatch;

async startRun() {
  this.#watch = await this.#geolocation.watchPosition(
    {
      distanceFilter: 10,
      // Android's notification while it runs. `true` shows the app's name.
      background: { title: 'Run in progress', text: 'Following your route' },
    },
    (position) => this.route.update((route) => [...route, position]),
  );
}

async endRun() {
  await this.#watch?.stop();
}
```

- **Start it while the app is on the screen.** It needs only the "while using the app" permission then. Android rejects one started from the background with `failed`.
- **The person sees it.** iOS shows its location indicator in the status bar while the app is away. Android shows a notification, which brings the app back when tapped. Android 13 and later show the notification only to an app allowed notifications, but the watch goes on either way.
- **Stop it when the run ends.** It drains the battery for as long as it runs.

### Hear when the phone enters an area

With `permissions.locationAlways` on, `watchRegion()` calls back with `enter` as the phone comes into a circle, and `exit` as it leaves, with the app open or in the background. The phones watch areas themselves, sparing the battery, so there's no watch to keep going:

```typescript
@Service()
export class ShopArrival {
  readonly #atShop = signal(false);
  readonly atShop = this.#atShop.asReadonly();

  constructor() {
    // A root service's watch lasts as long as the app runs.
    inject(LynxGeolocation)
      .watchRegion(
        { latitude: 51.5007, longitude: -0.1246, radius: 200 },
        (event) => this.#atShop.set(event === 'enter'),
      )
      .catch((error: GeolocationError) => console.warn(error.code));
  }
}
```

- **It needs the precise location all the time,** and asks for it first, as `requestPermission({ always: true })` does. Without it, it rejects with `denied`.
- **`enter` comes at once** when the phone is in the area as the watch starts. A phone outside it hears nothing until it comes in.
- **It's a little late.** The app hears about an area some seconds or minutes after the phone crosses it, and about areas under about 150 meters across late or not at all.
- **Only while the app runs.** An app the person or the phone has closed isn't started again for an area, and its areas stop with it.
- **iOS watches up to 20 areas** for an app at once, and ends those past it with `failed`.
- **The iOS [Simulator](/guide/glossary.md#simulator) can't watch areas.** `watchRegion()` rejects with `failed` there, even with the location allowed all the time. Try areas on a phone, or an Android [emulator](/guide/glossary.md#emulator), which can.

**Ask for the location all the time when the person can see why.** Google Play requires the app to say what it's for, on a screen of its own, before it asks. Then call `requestPermission({ always: true })`:

- **iOS** asks once. If the person hasn't been asked for the location at all, it's one prompt: "Allow While Using App" grants Always for now, and iOS asks the person whether to keep it the first time it would tell the app about an area in the background. Otherwise it's a second prompt, to change to Always. iOS doesn't say when the person keeps "While Using" there, nor that it showed no prompt (as after "Allow Once"), so it resolves as the prompt closes, or after 20 seconds without one. `always()` follows a later answer.
- **Android 10** asks in a prompt. **Android 11 and later** open the app's location settings, where the person picks "Allow all the time", and resolve as they come back.

## API

### `LynxGeolocation`

```typescript
@Injectable({ providedIn: 'root' })
class LynxGeolocation {
  readonly state: Signal<GeolocationState>;
  readonly always: Signal<boolean>;
  requestPermission(
    options?: GeolocationPermissionOptions,
  ): Promise<GeolocationState>;
  getCurrentPosition(
    options?: GeolocationOptions,
  ): Promise<GeolocationPosition>;
  watchPosition(
    options: GeolocationWatchOptions,
    onPosition: (position: GeolocationPosition) => void,
    config?: { injector?: Injector },
  ): Promise<GeolocationWatch>;
  watchRegion(
    region: GeolocationRegion,
    onChange: (event: GeolocationRegionEvent) => void,
    config?: { injector?: Injector },
  ): Promise<GeolocationWatch>;
}
```

| Platform                                          | What it uses                                                                                                                                                                                                                                                       |
| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| iOS                                               | Core Location (`CLLocationManager`); Precise Location turned off reads as `approximate`                                                                                                                                                                            |
| Android                                           | `LocationManager`: the fused provider from Android 12, GPS or the network before it; no Google Play services                                                                                                                                                       |
| [Web preview](/guide/glossary.md#web-preview)     | The browser's `navigator.geolocation`. A browser doesn't say how precise it's allowed to be, so an allowed location reads as `precise`. It watches areas with the page's own watch, which needs only the browser's permission, and a background watch as any other |
| Unit tests with the testing library               | Where [`setLocation()`](/api/testing-library/fakes/sensors.md#setlocation) puts the phone                                                                                                                                                                          |
| [Lynx Explorer](/guide/glossary.md#lynx-explorer) | `unsupported`: calls reject with `unavailable`                                                                                                                                                                                                                     |

### `state`

Whether the app may find the phone, and how closely, as a signal. Reading it never asks.

- **It's read when the service is created.** Until that first answer comes, a moment later, it's `unknown`.
- **It's kept up to date** as the person answers the prompt or turns Location on or off.
- **It's read again each time the app comes back to the foreground,** since the person can change it in Settings meanwhile.

### `always`

Whether the app may find the phone while it isn't in use too, as a signal: iOS's Always, or Android's "Allow all the time" (any location permission before Android 10). `watchRegion()` needs it.

- **It's false** while `state` doesn't allow the location, in an app without `permissions.locationAlways`, and always in the web preview, where a page finds the phone only while it's open.
- **It's kept up to date** as `state` is.
- **iOS reports it straight away** when the person allows the location in a prompt the app asked for Always with. iOS asks them later whether to keep it, and it turns false if they say no.

### `requestPermission(options?)`

Shows the system's prompt if the person hasn't been asked, and resolves with the `state` after they answer.

Once they've answered, it resolves at once without showing anything. Android is the exception: it asks again after a refusal, until the system stops asking (see `denied` below).

With `{ always: true }`, it then asks for the location all the time, which `always` reports once the person has answered (see [Hear when the phone enters an area](#hear-when-the-phone-enters-an-area)). It rejects with `unavailable` in an app without `permissions.locationAlways`.

In the web preview, the browser asks only as the page reads the location, so it reads it once. That can take up to 10 seconds even when the browser already has its answer: show the app as busy until it resolves. `always` asks for nothing more there.

### `getCurrentPosition(options?)`

Finds where the phone is now, asking first if the person hasn't been asked. It rejects with a `GeolocationError`:

- `denied` when the app isn't allowed
- `off` when Location is off
- `timeout` when no position came in time

It rejects with a `RangeError` when `timeout` isn't a positive number or `maximumAge` is negative.

| Option       | Default     | Means                                                                                                              |
| ------------ | ----------- | ------------------------------------------------------------------------------------------------------------------ |
| `accuracy`   | `'precise'` | `'precise'` uses GPS where it can; `'approximate'` is quicker and cheaper, enough for a city or a weather forecast |
| `timeout`    | `10_000`    | How long to wait, in milliseconds                                                                                  |
| `maximumAge` | `0`         | How old a position the phone already has may be, in milliseconds, to answer at once. 0 always finds it afresh      |

An app the person allowed only `approximate` gets an approximate position either way.

:::tip Pass a maximumAge in a simulator or emulator
A location you set in the iOS [Simulator](/guide/glossary.md#simulator) or an Android [emulator](/guide/glossary.md#emulator) is one fix, stamped when you set it. It isn't renewed while it stays put.

With the default of 0, `getCurrentPosition()` waits for a newer fix that never comes, and rejects with `timeout`. A phone keeps finding itself, so it doesn't need one.
:::

### `watchPosition(options, onPosition, config?)`

Calls `onPosition` with where the phone is, and again each time it moves. Several watches can run at once.

- **It resolves** with a `GeolocationWatch` once the watch has started, after asking for permission if the person hasn't been asked.
- **It rejects** as `getCurrentPosition()` does.
- **Called in an injection context,** such as a constructor, the watch stops when the component or service is destroyed. Pass an `injector` to tie it to another one.

| Option           | Default     | Means                                                                                                                                                                         |
| ---------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `accuracy`       | `'precise'` | As for `getCurrentPosition()`                                                                                                                                                 |
| `distanceFilter` | `0`         | How far the phone has to move, in meters, before the next position. 0 reports each one, about once a second                                                                   |
| `background`     | `false`     | `true`, or Android's notification as `{ title?, text? }`: the watch goes on in the background (see [Follow the phone in the background](#follow-the-phone-in-the-background)) |

A background watch rejects with `unavailable` in an app without `backgroundLocation`.

Watching drains the battery, `precise` most: stop the watch once the app has what it needs.

### `watchRegion(region, onChange, config?)`

Calls `onChange` with `enter` when the phone comes into `region`, and with `exit` when it leaves (see [Hear when the phone enters an area](#hear-when-the-phone-enters-an-area)).

- **It resolves** with a `GeolocationWatch` once the watch has started, after asking for the location all the time if the person hasn't been asked.
- **It rejects** with `denied` without the precise location all the time, `off` when Location is off, and `unavailable` in an app without `permissions.locationAlways`. It rejects with a `RangeError` for a latitude, longitude or radius out of range.
- **Called in an injection context,** the watch stops when the component or service is destroyed, as `watchPosition()`'s does.

| Field       | Means                                                                  |
| ----------- | ---------------------------------------------------------------------- |
| `latitude`  | The center's degrees north of the equator, from -90 to 90              |
| `longitude` | The center's degrees east of Greenwich, from -180 to 180               |
| `radius`    | How far the area reaches from the center, in meters: a positive number |

### `GeolocationWatch`

| Member     | Means                                                                                                           |
| ---------- | --------------------------------------------------------------------------------------------------------------- |
| `watching` | A signal: whether it's still running                                                                            |
| `error`    | A signal: why it ended on its own, such as Location being turned off (`off`) or the permission taken (`denied`) |
| `stop()`   | Ends it. Ending one that has ended does nothing                                                                 |

`watchPosition()` and `watchRegion()` both resolve with one.

### `GeolocationPosition`

| Field              | Means                                                                                       |
| ------------------ | ------------------------------------------------------------------------------------------- |
| `latitude`         | Degrees north of the equator (WGS 84)                                                       |
| `longitude`        | Degrees east of Greenwich                                                                   |
| `accuracy`         | How far off the coordinates may be, in meters. An approximate position is off by kilometers |
| `altitude`         | Meters above the WGS 84 ellipsoid, as the web gives it (not above sea level), or null       |
| `altitudeAccuracy` | How far off the altitude may be, in meters, or null                                         |
| `heading`          | Degrees clockwise from true north the phone is moving in, or null when it isn't moving      |
| `speed`            | Meters a second, or null                                                                    |
| `timestamp`        | When it was found, in milliseconds since 1970                                               |

### `GeolocationState`

| Value         | Means                                                                                                                  |
| ------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `unknown`     | The person hasn't been asked yet, so `requestPermission()` shows the prompt. Also briefly after the service is created |
| `denied`      | The person refused, or a policy such as parental controls forbids it                                                   |
| `approximate` | Allowed, to within a few kilometers                                                                                    |
| `precise`     | Allowed, as closely as the phone can tell                                                                              |
| `off`         | Location is off for the whole phone, whatever the app was allowed                                                      |
| `unsupported` | The host has no location: Lynx Explorer, or an app without `permissions.location`                                      |

- **`unknown` at first:** for a moment after the service is created, before the first answer, it's `unknown` whatever the person chose.
- **`denied` on Android:** Android 11 and later ask once more after a first refusal, and earlier versions until the person ticks "Don't ask again". After that, and on iOS, the person has to allow it in Settings.

### `GeolocationError`

An `Error` with a `code`:

| Code          | When                                                                                                                                                                                             |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `unavailable` | The host has no location module, or the app's angular.json doesn't turn on what the call needs: `backgroundLocation` for a background watch, `permissions.locationAlways` for `always` and areas |
| `denied`      | The app isn't allowed                                                                                                                                                                            |
| `off`         | Location is off                                                                                                                                                                                  |
| `timeout`     | No position came in time                                                                                                                                                                         |
| `busy`        | Another permission prompt is open, as Android shows one at a time                                                                                                                                |
| `failed`      | Anything else. The message has the platform's reason                                                                                                                                             |

## Testing

Each test starts where a fresh install does. The person hasn't been asked, and allows precise location when the app asks. The phone has no position, so `getCurrentPosition()` rejects with `timeout`.

- [`setLocation()`](/api/testing-library/fakes/sensors.md#setlocation) puts the phone somewhere, sends each running watch the new position, and each area `enter` or `exit` as the phone crosses it.
- [`setLocationPermission()`](/api/testing-library/fakes/sensors.md#setlocationpermission) sets what the app is allowed.
- [`setLocationAlways()`](/api/testing-library/fakes/sensors.md#setlocationalways) sets whether it's allowed all the time.
- [`setLocationAnswer()`](/api/testing-library/fakes/sensors.md#setlocationanswer) and [`setLocationAlwaysAnswer()`](/api/testing-library/fakes/sensors.md#setlocationalwaysanswer) set what the prompts answer.
- [`setLocationEnabled()`](/api/testing-library/fakes/sensors.md#setlocationenabled) turns Location off.
- [`locationPrompts()`](/api/testing-library/fakes/sensors.md#locationprompts) counts the prompts shown.

A background watch runs as any other: the fake is an app with both settings.

```typescript
import {
  render,
  screen,
  setLocation,
  setLocationPermission,
} from '@blotch/angular-lynx-testing-library';

setLocationPermission('precise');
setLocation({ latitude: 51.5007, longitude: -0.1246 });
await render(Nearby);
```

## Related

- [Permission reasons](/guide/native-apps/permissions.md): the `location` reason and the other `permissions`
- [Turn on device features](/guide/native-apps/device-features.md): every opt-in build option
- [`LynxAppState`](/api/angular-lynx/device/app-state.md): stop a watch while the app is in the background
- [`LynxLinking.openAppSettings()`](/api/angular-lynx/sharing/linking.md#lynxlinkingopenappsettings): where a person who refused allows the location
