For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/angular-lynx/hardware/geolocation.md.

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 iOS shows when it asks:

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:

angular.json
"options": {
  "backgroundLocation": true,
  "permissions": {
    "location": "Follows your run on the map",
    "locationAlways": "Tells you when you reach the shop"
  }
}
SettingLets the appAdds
backgroundLocationKeep 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.locationAlwaysAsk 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 for every setting.

Usage

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:

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

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:

@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 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, 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

@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>;
}
PlatformWhat it uses
iOSCore Location (CLLocationManager); Precise Location turned off reads as approximate
AndroidLocationManager: the fused provider from Android 12, GPS or the network before it; no Google Play services
Web previewThe 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 libraryWhere setLocation() puts the phone
Lynx Explorerunsupported: 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). 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.

OptionDefaultMeans
accuracy'precise''precise' uses GPS where it can; 'approximate' is quicker and cheaper, enough for a city or a weather forecast
timeout10_000How long to wait, in milliseconds
maximumAge0How 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.

Pass a maximumAge in a simulator or emulator

A location you set in the iOS Simulator or an Android 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.
OptionDefaultMeans
accuracy'precise'As for getCurrentPosition()
distanceFilter0How far the phone has to move, in meters, before the next position. 0 reports each one, about once a second
backgroundfalsetrue, or Android's notification as { title?, text? }: the watch goes on in the background (see 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).

  • 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.
FieldMeans
latitudeThe center's degrees north of the equator, from -90 to 90
longitudeThe center's degrees east of Greenwich, from -180 to 180
radiusHow far the area reaches from the center, in meters: a positive number

GeolocationWatch

MemberMeans
watchingA signal: whether it's still running
errorA 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

FieldMeans
latitudeDegrees north of the equator (WGS 84)
longitudeDegrees east of Greenwich
accuracyHow far off the coordinates may be, in meters. An approximate position is off by kilometers
altitudeMeters above the WGS 84 ellipsoid, as the web gives it (not above sea level), or null
altitudeAccuracyHow far off the altitude may be, in meters, or null
headingDegrees clockwise from true north the phone is moving in, or null when it isn't moving
speedMeters a second, or null
timestampWhen it was found, in milliseconds since 1970

GeolocationState

ValueMeans
unknownThe person hasn't been asked yet, so requestPermission() shows the prompt. Also briefly after the service is created
deniedThe person refused, or a policy such as parental controls forbids it
approximateAllowed, to within a few kilometers
preciseAllowed, as closely as the phone can tell
offLocation is off for the whole phone, whatever the app was allowed
unsupportedThe 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:

CodeWhen
unavailableThe 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
deniedThe app isn't allowed
offLocation is off
timeoutNo position came in time
busyAnother permission prompt is open, as Android shows one at a time
failedAnything 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.

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

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

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