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.

A street map along the Vistula below Wawel at zoom 19, turned to the bicycle's heading, with the position marker on Bulwar Czerwieński and the readings of the simulated ride in the top right corner.
A screenshot of the example. Map data © OpenStreetMap contributors.

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.ts
import {
  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();
  }
}

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 LineString with 'XYZM' layout where Z holds unwrapped heading in radians and M holds the fix timestamp.
  • Each render frame triggers updateView from [postrender], interpolating X, Y and heading 1.5 sampling intervals earlier via getCoordinateAtM.
  • setRotation aligns 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°: addPosition keeps 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.

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.