Essentials · Angular, React and OpenLayers

The user's position from the Geolocation API

Track browser GPS position on an OpenLayers map with an accuracy polygon and live altitude, heading and speed read-outs in Angular and React.

A street map of Kraków's Old Town at zoom 15 with a blue point on the Main Square inside its accuracy circle, and the read-outs below it: an accuracy of 150 m and dashes for the altitude, heading and speed that the browser does not report.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Over a street map of Kraków, toggling the tracking checkbox activates the browser’s Geolocation API, draws the reported position point together with its projected accuracy circle on the map, and updates live diagnostic read-outs below the viewport for accuracy, altitude, heading and speed.

Metrics that the current device cannot measure—such as altitude, heading and speed on a stationary Wi-Fi desktop—display clean placeholder dashes, while denied permissions or insecure origins surface clear error messages.

When you need it

Field-inspection apps, municipal asset surveys, outdoor trail guides and store locators begin by showing users where they stand—and how much uncertainty surrounds that fix.

Plotting a bare dot without its uncertainty radius misleads users when indoor Wi-Fi or cell-tower positioning is off by 150 metres or more; pairing the point with OpenLayers’ projected accuracy polygon communicates positional confidence immediately.

The code

The example uses cc-openlayers, my Angular component library for OpenLayers: each aol-… element creates the OpenLayers object it names, updates it from its inputs and disposes of it with the component.

geolocation.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import type { GeolocationError } from 'ol/Geolocation';
import type Geometry from 'ol/geom/Geometry';
import Point from 'ol/geom/Point';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  FeatureComponent,
  GeolocationComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  SourceOsmComponent,
  SourceVectorComponent,
  StyleCircleComponent,
  StyleComponent,
  StyleFillComponent,
  StyleStrokeComponent,
  ViewComponent,
} from 'cc-openlayers';

/** What the browser reports besides the position, as the read-outs show it. */
interface Reading {
  accuracy: string;
  altitude: string;
  altitudeAccuracy: string;
  heading: string;
  speed: string;
}

const NOTHING_YET: Reading = { accuracy: '–', altitude: '–', altitudeAccuracy: '–', heading: '–', speed: '–' };

/** The browser's position on the map, with its accuracy circle and the other values the Geolocation API gives. */
@Component({
  selector: 'app-geolocation',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    FeatureComponent,
    GeolocationComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    SourceOsmComponent,
    SourceVectorComponent,
    StyleCircleComponent,
    StyleComponent,
    StyleFillComponent,
    StyleStrokeComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="13">
        <aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
      <!-- enableHighAccuracy must be true to get a heading. -->
      <aol-geolocation
        [tracking]="tracking()"
        [trackingOptions]="{ enableHighAccuracy: true }"
        (changePosition)="moved()"
        (changeAccuracyGeometry)="accuracy.set(geolocation().instance.getAccuracyGeometry() ?? undefined)"
        (changeHeading)="read()"
        (changeSpeed)="read()"
        (error)="failed($event)"
      />
      <aol-layer-vector>
        <aol-source-vector>
          <aol-feature id="accuracy" [geometry]="accuracy()" />
          <aol-feature id="position" [geometry]="position()">
            <aol-style>
              <aol-style-circle [radius]="6">
                <aol-style-fill color="#3399CC" />
                <aol-style-stroke color="#fff" [width]="2" />
              </aol-style-circle>
            </aol-style>
          </aol-feature>
        </aol-source-vector>
      </aol-layer-vector>
    </aol-map>
    <div class="example-controls">
      <label>
        <input type="checkbox" [checked]="tracking()" (change)="tracking.set(checked($event))" />
        Track position
      </label>
      <label
        >Position accuracy <output>{{ reading().accuracy }} m</output></label
      >
      <label
        >Altitude <output>{{ reading().altitude }} m</output></label
      >
      <label
        >Altitude accuracy <output>{{ reading().altitudeAccuracy }} m</output></label
      >
      <label
        >Heading <output>{{ reading().heading }} rad</output></label
      >
      <label
        >Speed <output>{{ reading().speed }} m/s</output></label
      >
      @if (error(); as message) {
        <p class="example-hint" role="alert">{{ message }}</p>
      }
    </div>
  `,
})
export class Geolocation {
  readonly tracking = signal(false);
  readonly reading = signal(NOTHING_YET);
  readonly error = signal('');
  protected readonly position = signal<Geometry | undefined>(undefined);
  protected readonly accuracy = signal<Geometry | undefined>(undefined);
  protected readonly geolocation = viewChild.required(GeolocationComponent);

  /** Moves the point to the new position and updates the read-outs. */
  protected moved(): void {
    const coordinates = this.geolocation().instance.getPosition();
    this.position.set(coordinates ? new Point(coordinates) : undefined);
    this.read();
  }

  protected read(): void {
    const geolocation = this.geolocation().instance;
    const text = (value: number | undefined) => (value === undefined ? '–' : String(value));
    this.reading.set({
      accuracy: text(geolocation.getAccuracy()),
      altitude: text(geolocation.getAltitude()),
      altitudeAccuracy: text(geolocation.getAltitudeAccuracy()),
      heading: text(geolocation.getHeading()),
      speed: text(geolocation.getSpeed()),
    });
  }

  protected failed(event: GeolocationError): void {
    this.error.set(event.message);
  }

  protected checked(event: Event): boolean {
    return (event.target as HTMLInputElement).checked;
  }
}

Architecture and OpenLayers mechanics

aol-geolocation wraps OpenLayers’ Geolocation helper, syncing its projection with the map view and toggling active sensor watch queries via [tracking]. Requesting [trackingOptions]="{ enableHighAccuracy: true }" opts mobile devices into GNSS satellite fixes rather than coarse network location, which is also prerequisite for valid movement heading and ground speed.

Whenever new sensor fixes arrive, (changePosition) updates a point feature’s coordinates and (changeAccuracyGeometry) supplies a ready-made circular polygon projected in map space, while (error) captures permission denials or timeouts.

How it works

  • aol-geolocation manages the browser Geolocation watcher and starts or stops continuous updates through its [tracking] binding.
  • [trackingOptions]="{ enableHighAccuracy: true }" requests GNSS-grade positioning on capable devices so heading and speed can be reported.
  • (changePosition) and (changeAccuracyGeometry) update the position marker and accuracy polygon directly in the map’s projection.
  • Read-outs report accuracy and altitude in metres, clockwise heading in radians and speed in metres per second, falling back to dashes when unavailable.

Pitfalls

  • Modern browsers restrict Geolocation strictly to secure contexts (HTTPS or localhost) and explicit user consent; always wire (error) so denied permissions explain why no marker appears.
  • Desktop browsers without GPS hardware estimate location from IP or Wi-Fi networks—often hundreds of metres wide and with null heading and speed—so always render the accuracy geometry alongside the point.
  • Continuous high-accuracy GNSS tracking drains mobile batteries rapidly: disable tracking when the component unmounts or the user turns location following off.

The same feature in the OpenLayers examples .

Background: state and lifecycle of maps in Angular with OpenLayers, which the components of cc-openlayers take care of.