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.

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.tsimport { 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;
}
} The React version uses the library's React adapter, cc-openlayers/react: each component creates the OpenLayers object it names when it mounts, updates it from its props and disposes of it when it unmounts.
geolocation.react.tsximport { useState } from 'react';
import type OLGeolocation from 'ol/Geolocation.js';
import type { GeolocationError } from 'ol/Geolocation.js';
import type Geometry from 'ol/geom/Geometry.js';
import Point from 'ol/geom/Point.js';
import {
CircleStyle,
Coordinate,
DefaultControls,
DefaultInteractions,
Feature,
Fill,
Geolocation as GeolocationControl,
Map,
OSMSource,
Stroke,
Style,
TileLayer,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
/** 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: '–' };
/** enableHighAccuracy must be true to get a heading. */
const TRACKING_OPTIONS = { enableHighAccuracy: true };
/** The browser's position on the map, with its accuracy circle and the other values the Geolocation API gives. */
export function Geolocation() {
const [tracking, setTracking] = useState(false);
const [reading, setReading] = useState(NOTHING_YET);
const [error, setError] = useState('');
const [position, setPosition] = useState<Geometry | undefined>(undefined);
const [accuracy, setAccuracy] = useState<Geometry | undefined>(undefined);
/** Moves the point to the new position and updates the read-outs. */
const moved = (current: OLGeolocation) => {
const coordinates = current.getPosition();
setPosition(coordinates ? new Point(coordinates) : undefined);
read(current);
};
const read = (current: OLGeolocation) => {
const text = (value: number | undefined) => (value === undefined ? '–' : String(value));
setReading({
accuracy: text(current.getAccuracy()),
altitude: text(current.getAltitude()),
altitudeAccuracy: text(current.getAltitudeAccuracy()),
heading: text(current.getHeading()),
speed: text(current.getSpeed()),
});
};
const failed = (event: GeolocationError) => setError(event.message);
return (
<>
<Map height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={13}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
<GeolocationControl
tracking={tracking}
trackingOptions={TRACKING_OPTIONS}
onChangePosition={(event) => moved(event.target as OLGeolocation)}
onChangeAccuracyGeometry={(event) =>
setAccuracy((event.target as OLGeolocation).getAccuracyGeometry() ?? undefined)
}
onChangeHeading={(event) => read(event.target as OLGeolocation)}
onChangeSpeed={(event) => read(event.target as OLGeolocation)}
onError={failed}
/>
<VectorLayer>
<VectorSource>
<Feature id="accuracy" geometry={accuracy} />
<Feature id="position" geometry={position}>
<Style>
<CircleStyle radius={6}>
<Fill color="#3399CC" />
<Stroke color="#fff" width={2} />
</CircleStyle>
</Style>
</Feature>
</VectorSource>
</VectorLayer>
</Map>
<div className="example-controls">
<label>
<input type="checkbox" checked={tracking} onChange={(event) => setTracking(event.target.checked)} />
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>
{error ? (
<p className="example-hint" role="alert">
{error}
</p>
) : null}
</div>
</>
);
}How the React version works
A checkbox turns position tracking on. A point shows the position the browser reports, a polygon its accuracy, and the accuracy, altitude, heading and speed appear below the map. A browser error becomes a message. The example shows the adapter's Geolocation component and its change events.
What both versions share
OpenLayers renders the map and handles the interactions; the cc-openlayers/core layer gives both adapters the same view binding (MapViewBinding) and the same conversion of coordinates from EPSG:4326 to the map's projection. ol/Geolocation computes the position and the accuracy geometry; both versions ask for high accuracy (enableHighAccuracy), without which the browser reports no heading.
From Angular to React
| Angular | React |
|---|---|
<aol-geolocation [tracking]="tracking()"> | <Geolocation tracking={tracking}> (imported as GeolocationControl, because the name Geolocation belongs to the example's component) |
(changePosition), (changeAccuracyGeometry), (changeHeading), (changeSpeed), (error) | onChangePosition, onChangeAccuracyGeometry, onChangeHeading, onChangeSpeed, onError |
viewChild.required(GeolocationComponent).instance in the handlers | the OpenLayers event's event.target |
[trackingOptions]="{ enableHighAccuracy: true }" | the module constant TRACKING_OPTIONS |
<aol-feature [geometry]="position()"> | <Feature geometry={position}> |
Who creates, updates and disposes
Map creates the ol/Map in useLayoutEffect and disposes of it on unmount; each layer, source and interaction component adds its object to the parent it gets from context and removes it in its effect's cleanup, as ngOnDestroy does in Angular. Geolocation creates the ol/Geolocation with the map view's projection and disposes of it on unmount; a change of tracking only calls setTracking. The tracking options are a module constant, because a new object on every render would be a new value to the adapter.
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-geolocationmanages 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.
Related examples
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.