Essentials · Angular, React and OpenLayers
Follow the device with its heading up
Follow a moving device heading-up on an OpenLayers map with XYZM trajectory smoothing and a simulated bike ride along Kraków’s Vistula river.

What this example shows
Zoomed to street level along Bulwar Czerwieński below Wawel Castle, this example rotates the map continuously so the user’s direction of travel points straight up the screen and offsets the position marker three-quarters of the way down the viewport to maximise visibility ahead.
A Simulate action replays a recorded bicycle trajectory along the Vistula embankment with live speed and heading readings, demonstrating fluid 60 fps camera tracking between coarse GPS fixes.
When you need it
Turn-by-turn cycling navigation, logistics fleet guidance and field-crew tracking apps need automotive-style “heading-up” camera motion rather than north-up jumps once per second.
Raw GPS hardware typically reports positions at 1 Hz; snapping camera centre and rotation directly to each raw fix produces a jarring, stepped jump every second unless positions and headings are interpolated across render frames.
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-orientation.tsimport {
afterNextRender,
ChangeDetectionStrategy,
Component,
DestroyRef,
PendingTasks,
inject,
signal,
viewChild,
} from '@angular/core';
import type { Coordinate } from 'ol/coordinate';
import LineString from 'ol/geom/LineString';
import { modulo, toDegrees, toRadians } from 'ol/math';
import { fromLonLat } from 'ol/proj';
import {
ContentComponent,
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
GeolocationComponent,
LayerTileComponent,
MapComponent,
OverlayComponent,
SourceOsmComponent,
ViewComponent,
} from 'cc-openlayers';
/** One position as a phone's Geolocation API reports it, as assets/krakow/bike-ride.json keeps them. */
interface Report {
coords: { longitude: number; latitude: number; accuracy: number; heading: number; speed: number };
timestamp: number;
}
const MARKER = 'assets/krakow/geolocation-marker.svg';
const MARKER_HEADING = 'assets/krakow/geolocation-marker-heading.svg';
/**
* A map that follows the device with its heading up: the reported positions are kept as a time-aware line, and each
* frame shows where the device was one and a half sampling periods ago, so the view moves smoothly between reports.
* "Simulate" replays a bicycle ride along the Vistula below Wawel at half speed instead of the device's positions.
*/
@Component({
selector: 'app-geolocation-orientation',
imports: [
ContentComponent,
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
GeolocationComponent,
LayerTileComponent,
MapComponent,
OverlayComponent,
SourceOsmComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="geolocation-orientation">
<aol-map height="480px">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="19">
<aol-coordinate [x]="19.9297" [y]="50.0551" srid="EPSG:4326" />
</aol-view>
<aol-layer-tile [postrender]="following() ? updateView : undefined"><aol-source-osm /></aol-layer-tile>
<aol-geolocation
[tracking]="tracking()"
[trackingOptions]="trackingOptions"
(error)="error.set('geolocation error')"
/>
<aol-overlay positioning="center-center" [stopEvent]="false">
<aol-content><img [src]="marker()" alt="" /></aol-content>
</aol-overlay>
</aol-map>
@if (info().length) {
<div class="geolocation-info">
@for (line of info(); track $index) {
<span>{{ line }}</span
><br />
}
</div>
}
<div class="geolocate-buttons">
<button type="button" class="primary" [disabled]="following()" (click)="geolocate()">Geolocate Me!</button>
<button type="button" [disabled]="following()" (click)="simulate()">Simulate</button>
</div>
</div>
@if (error()) {
<p class="example-hint" role="alert">{{ error() }}</p>
}
`,
})
export class GeolocationOrientation {
protected readonly trackingOptions = { maximumAge: 10000, enableHighAccuracy: true, timeout: 600000 };
protected readonly tracking = signal(false);
/** Whether the view follows the positions, from "Geolocate Me!" or "Simulate" on. */
protected readonly following = signal(false);
protected readonly info = signal<string[]>([]);
protected readonly marker = signal(MARKER);
protected readonly error = signal('');
private readonly map = viewChild.required(MapComponent);
private readonly geolocation = viewChild.required(GeolocationComponent);
private readonly overlay = viewChild.required(OverlayComponent);
/** The reported positions as a time-aware line: the heading is kept as Z and the time as M. */
private readonly positions = new LineString([], 'XYZM');
/** The mean time between two reports, in milliseconds. */
private deltaMean = 500;
private previousM = 0;
private simulationData: Report[] = [];
private timer?: ReturnType<typeof setTimeout>;
constructor() {
void inject(PendingTasks).run(async () => {
const ride = (await (await fetch('assets/krakow/bike-ride.json')).json()) as { data: Report[] };
this.simulationData = ride.data;
});
afterNextRender(() => this.geolocation().instance.on('change', () => this.changed()));
inject(DestroyRef).onDestroy(() => clearTimeout(this.timer));
}
/** Starts tracking the device. */
protected geolocate(): void {
this.tracking.set(true);
this.follow();
}
/** Replays the recorded ride: each report after twice the time it came after the one before. */
protected simulate(): void {
const coordinates = [...this.simulationData];
const first = coordinates.shift();
if (!first) return;
this.simulatePositionChange(first);
let prevDate = first.timestamp;
const geolocate = () => {
const position = coordinates.shift();
if (!position) {
return;
}
const newDate = position.timestamp;
this.simulatePositionChange(position);
this.timer = setTimeout(
() => {
prevDate = newDate;
geolocate();
},
(newDate - prevDate) / 0.5
);
};
geolocate();
this.follow();
}
/** Shows, on each frame, where the device was one and a half sampling periods ago: between two reports. */
protected readonly updateView = (): void => {
let m = Date.now() - this.deltaMean * 1.5;
m = Math.max(m, this.previousM);
this.previousM = m;
// Interpolated along the line of the reported positions.
const c = this.positions.getCoordinateAtM(m, true);
if (c) {
const map = this.map().instance;
const view = map.getView();
view.setCenter(this.getCenterWithHeading(c, -c[2], view.getResolution() ?? 0));
view.setRotation(-c[2]);
this.overlay().instance.setPosition(c);
map.render();
}
};
private follow(): void {
this.following.set(true);
this.map().instance.render();
}
private changed(): void {
const geolocation = this.geolocation().instance;
const position = geolocation.getPosition();
if (!position) return;
const accuracy = geolocation.getAccuracy();
const heading = geolocation.getHeading() || 0;
const speed = geolocation.getSpeed() || 0;
const m = Date.now();
this.addPosition(position, heading, m, speed);
const coords = this.positions.getCoordinates();
const len = coords.length;
if (len >= 2) {
this.deltaMean = (coords[len - 1][3] - coords[0][3]) / (len - 1);
}
this.info.set([
'Position: ' + position[0].toFixed(2) + ', ' + position[1].toFixed(2),
'Accuracy: ' + accuracy,
'Heading: ' + Math.round(toDegrees(heading)) + '°',
'Speed: ' + (speed * 3.6).toFixed(1) + ' km/h',
'Delta: ' + Math.round(this.deltaMean) + 'ms',
]);
}
private addPosition(position: Coordinate, heading: number, m: number, speed: number): void {
const x = position[0];
const y = position[1];
const fCoords = this.positions.getCoordinates();
const previous = fCoords[fCoords.length - 1];
const prevHeading = previous && previous[2];
if (prevHeading) {
let headingDiff = heading - modulo(prevHeading, 2 * Math.PI);
// force the rotation change to be less than 180°
if (Math.abs(headingDiff) > Math.PI) {
const sign = headingDiff >= 0 ? 1 : -1;
headingDiff = -sign * (2 * Math.PI - Math.abs(headingDiff));
}
heading = prevHeading + headingDiff;
}
this.positions.appendCoordinate([x, y, heading, m]);
// only keep the 20 last coordinates
this.positions.setCoordinates(this.positions.getCoordinates().slice(-20));
this.marker.set(heading && speed ? MARKER_HEADING : MARKER);
}
/** The centre that puts the position three quarters down the map, leaving more of it ahead of the device. */
private getCenterWithHeading(position: Coordinate, rotation: number, resolution: number): Coordinate {
const size = this.map().instance.getSize() ?? [0, 0];
const height = size[1];
return [
position[0] - (Math.sin(rotation) * height * resolution * 1) / 4,
position[1] + (Math.cos(rotation) * height * resolution * 1) / 4,
];
}
private simulatePositionChange(position: Report): void {
const coords = position.coords;
const geolocation = this.geolocation().instance;
geolocation.set('accuracy', coords.accuracy);
geolocation.set('heading', toRadians(coords.heading));
const projectedPosition = fromLonLat([coords.longitude, coords.latitude]);
geolocation.set('position', projectedPosition);
geolocation.set('speed', coords.speed);
geolocation.changed();
}
} 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-orientation.react.tsximport { Fragment, useCallback, useEffect, useEffectEvent, useRef, useState } from 'react';
import type OLGeolocation from 'ol/Geolocation.js';
import type { Coordinate as OLCoordinate } from 'ol/coordinate.js';
import LineString from 'ol/geom/LineString.js';
import type OLMap from 'ol/Map.js';
import { modulo, toDegrees, toRadians } from 'ol/math.js';
import type OLOverlay from 'ol/Overlay.js';
import { fromLonLat } from 'ol/proj.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
Geolocation,
Map,
OSMSource,
Overlay,
TileLayer,
View,
} from 'cc-openlayers/react';
/** One position as a phone's Geolocation API reports it, as assets/krakow/bike-ride.json keeps them. */
interface Report {
coords: { longitude: number; latitude: number; accuracy: number; heading: number; speed: number };
timestamp: number;
}
const MARKER = 'assets/krakow/geolocation-marker.svg';
const MARKER_HEADING = 'assets/krakow/geolocation-marker-heading.svg';
const TRACKING_OPTIONS = { maximumAge: 10000, enableHighAccuracy: true, timeout: 600000 };
/** The centre that puts the position three quarters down the map, leaving more of it ahead of the device. */
function getCenterWithHeading(
position: OLCoordinate,
rotation: number,
resolution: number,
size: number[] | undefined
): OLCoordinate {
const height = (size ?? [0, 0])[1];
return [
position[0] - (Math.sin(rotation) * height * resolution * 1) / 4,
position[1] + (Math.cos(rotation) * height * resolution * 1) / 4,
];
}
/**
* A map that follows the device with its heading up: the reported positions are kept as a time-aware line, and each
* frame shows where the device was one and a half sampling periods ago, so the view moves smoothly between reports.
* "Simulate" replays a bicycle ride along the Vistula below Wawel at half speed instead of the device's positions.
*/
export function GeolocationOrientation() {
const [tracking, setTracking] = useState(false);
/** Whether the view follows the positions, from "Geolocate Me!" or "Simulate" on. */
const [following, setFollowing] = useState(false);
const [info, setInfo] = useState<string[]>([]);
const [marker, setMarker] = useState(MARKER);
const [error, setError] = useState('');
const map = useRef<OLMap>(null);
const overlay = useRef<OLOverlay>(null);
// The geolocation joins the map after it, so the listener below waits for it.
const [geolocation, setGeolocation] = useState<OLGeolocation | null>(null);
/** The reported positions as a time-aware line: the heading is kept as Z and the time as M. */
const [positions] = useState(() => new LineString([], 'XYZM'));
/** The mean time between two reports, in milliseconds. */
const deltaMean = useRef(500);
const previousM = useRef(0);
const simulationData = useRef<Report[]>([]);
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => {
void fetch('assets/krakow/bike-ride.json')
.then((response) => response.json() as Promise<{ data: Report[] }>)
.then((ride) => {
simulationData.current = ride.data;
});
return () => clearTimeout(timer.current);
}, []);
const addPosition = (position: OLCoordinate, heading: number, m: number, speed: number) => {
const x = position[0];
const y = position[1];
const fCoords = positions.getCoordinates();
const previous = fCoords[fCoords.length - 1];
const prevHeading = previous && previous[2];
if (prevHeading) {
let headingDiff = heading - modulo(prevHeading, 2 * Math.PI);
// force the rotation change to be less than 180°
if (Math.abs(headingDiff) > Math.PI) {
const sign = headingDiff >= 0 ? 1 : -1;
headingDiff = -sign * (2 * Math.PI - Math.abs(headingDiff));
}
heading = prevHeading + headingDiff;
}
positions.appendCoordinate([x, y, heading, m]);
// only keep the 20 last coordinates
positions.setCoordinates(positions.getCoordinates().slice(-20));
setMarker(heading && speed ? MARKER_HEADING : MARKER);
};
const changed = useEffectEvent((current: OLGeolocation) => {
const position = current.getPosition();
if (!position) return;
const accuracy = current.getAccuracy();
const heading = current.getHeading() || 0;
const speed = current.getSpeed() || 0;
const m = Date.now();
addPosition(position, heading, m, speed);
const coords = positions.getCoordinates();
const len = coords.length;
if (len >= 2) {
deltaMean.current = (coords[len - 1][3] - coords[0][3]) / (len - 1);
}
setInfo([
'Position: ' + position[0].toFixed(2) + ', ' + position[1].toFixed(2),
'Accuracy: ' + accuracy,
'Heading: ' + Math.round(toDegrees(heading)) + '°',
'Speed: ' + (speed * 3.6).toFixed(1) + ' km/h',
'Delta: ' + Math.round(deltaMean.current) + 'ms',
]);
});
useEffect(() => {
if (!geolocation) return;
const listener = () => changed(geolocation);
geolocation.on('change', listener);
return () => geolocation.un('change', listener);
}, [geolocation]);
const follow = () => {
setFollowing(true);
map.current?.render();
};
/** Starts tracking the device. */
const geolocate = () => {
setTracking(true);
follow();
};
const simulatePositionChange = (position: Report) => {
const coords = position.coords;
if (!geolocation) return;
geolocation.set('accuracy', coords.accuracy);
geolocation.set('heading', toRadians(coords.heading));
const projectedPosition = fromLonLat([coords.longitude, coords.latitude]);
geolocation.set('position', projectedPosition);
geolocation.set('speed', coords.speed);
geolocation.changed();
};
/** Replays the recorded ride: each report after twice the time it came after the one before. */
const simulate = () => {
const coordinates = [...simulationData.current];
const first = coordinates.shift();
if (!first) return;
simulatePositionChange(first);
let prevDate = first.timestamp;
const replay = () => {
const position = coordinates.shift();
if (!position) {
return;
}
const newDate = position.timestamp;
simulatePositionChange(position);
timer.current = setTimeout(
() => {
prevDate = newDate;
replay();
},
(newDate - prevDate) / 0.5
);
};
replay();
follow();
};
/** Shows, on each frame, where the device was one and a half sampling periods ago: between two reports. */
const updateView = useCallback(() => {
let m = Date.now() - deltaMean.current * 1.5;
m = Math.max(m, previousM.current);
previousM.current = m;
// Interpolated along the line of the reported positions.
const c = positions.getCoordinateAtM(m, true);
const current = map.current;
if (c && current) {
const view = current.getView();
view.setCenter(getCenterWithHeading(c, -c[2], view.getResolution() ?? 0, current.getSize()));
view.setRotation(-c[2]);
overlay.current?.setPosition(c);
current.render();
}
}, [positions]);
return (
<>
<div className="geolocation-orientation">
<Map ref={map} height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={19}>
<Coordinate x={19.9297} y={50.0551} srid="EPSG:4326" />
</View>
<TileLayer onPostRender={following ? updateView : undefined}>
<OSMSource />
</TileLayer>
<Geolocation
ref={setGeolocation}
tracking={tracking}
trackingOptions={TRACKING_OPTIONS}
onError={() => setError('geolocation error')}
/>
<Overlay ref={overlay} positioning="center-center" stopEvent={false}>
<img src={marker} alt="" />
</Overlay>
</Map>
{info.length ? (
<div className="geolocation-info">
{info.map((line, index) => (
<Fragment key={index}>
<span>{line}</span>
<br />
</Fragment>
))}
</div>
) : null}
<div className="geolocate-buttons">
<button type="button" className="primary" disabled={following} onClick={geolocate}>
Geolocate Me!
</button>
<button type="button" disabled={following} onClick={simulate}>
Simulate
</button>
</div>
</div>
{error ? (
<p className="example-hint" role="alert">
{error}
</p>
) : null}
</>
);
}How the React version works
The map follows the device like a navigation app: the heading points up and the position sits a quarter of the map lower. Movement between readings is smoothed. The “Simulate” button replays a recorded bike ride along the Vistula below Wawel at half speed, so the example works without GPS. The marker becomes an arrow while the device moves with a heading.
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. The XYZM line of the last 20 readings (heading as Z, time as M), the rotation the shorter way through north and the getCoordinateAtM interpolation are the same in both versions; the recorded ride is assets/krakow/bike-ride.json.
From Angular to React
| Angular | React |
|---|---|
viewChild.required(GeolocationComponent) and a change listener in afterNextRender | ref={setGeolocation} (state) and a useEffect that subscribes to change once the object exists |
| a handler reading the current class fields | useEffectEvent: the listener is subscribed once and the handler always sees the latest state |
[postrender]="following() ? updateView : undefined" on the layer | onPostRender={following ? updateView : undefined} on TileLayer |
<aol-overlay> with <aol-content> | <Overlay ref={overlay}> with the marker image |
DestroyRef.onDestroy clearing the simulation timer | the useEffect cleanup |
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. Fetching the recording and the replay timer live in an effect whose cleanup stops the replay on unmount. The position line is created once in a useState initialiser.
Architecture and OpenLayers mechanics
Incoming fixes are appended into an OpenLayers LineString configured with the four-dimensional 'XYZM' coordinate layout—storing map X and Y in the first two ordinates, unwrapped cumulative heading in Z, and timestamp in M. On every animation frame, the tile layer’s [postrender] hook calls updateView, which samples getCoordinateAtM one-and-a-half reporting intervals behind the latest timestamp.
Interpolating slightly behind live sensor time guarantees two bracketing points exist on the trajectory, letting setRotation spin the camera smoothly and position the user marker three quarters of the way down the screen while addPosition unwraps 359° → 0° compass crossings.
How it works
- Reported fixes accumulate in a
LineStringwith'XYZM'layout where Z holds unwrapped heading in radians and M holds the fix timestamp. - Each render frame triggers
updateViewfrom[postrender], interpolating X, Y and heading 1.5 sampling intervals earlier viagetCoordinateAtM. setRotationaligns the view heading-up while positioning the user marker three-quarters down the viewport so more route ahead stays visible.- A built-in simulator replays a Vistula riverside ride to test heading-up smoothing on desktops without walking outdoors.
Pitfalls
- Raw compass headings jump discontinuously between 359° and 0°:
addPositionkeeps consecutive angular deltas under 180° so the map does not spin 359° the wrong way across north. - Sampling 1.5 intervals behind real time introduces a tiny intentional lag (~1–1.5 s) in exchange for jitter-free 60 fps interpolation.
- Configure the HTML marker overlay with
[stopEvent]="false"so touch drags starting on top of the rider icon still pan or zoom the map.
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.