Overlays and animation · Angular, React and OpenLayers

A marker moving along a route

Animate a marker smoothly out and back along a decoded Polyline route in OpenLayers using delta-time postrender updates and a speed slider.

The orthophotomap of Kraków with a yellow route from a blue pin on the Main Square to one in Nowa Huta, the black marker on its way, and Speed 60 and Stop Animation below the map.
A screenshot of the example. Orthophotomap © GUGiK. Map data © OpenStreetMap contributors.

What this example shows

Over Kraków’s aerial orthophotomap, a yellow route decoded from an encoded polyline connects pins on the Main Square and in Nowa Huta. Clicking Start / Stop Animation glides a black marker smoothly along every street turn out to Nowa Huta and back at a pace controlled live by the Speed slider—parking cleanly at its exact spot whenever paused.

When you need it

Delivery trackers, courier replays, public-transit simulators and turn-by-turn route previews animate a vehicle or runner smoothly along a road-network polyline.

Drawing the moving marker inside postrender avoids mutating source Feature geometries 60 times per second—preventing expensive spatial-index rebuilds of the static route layer.

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.

feature-move-animation.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import Polyline from 'ol/format/Polyline';
import type LineString from 'ol/geom/LineString';
import Point from 'ol/geom/Point';
import { getTopLeft, getWidth } from 'ol/extent';
import { EXTENT } from 'ol/proj/epsg3857';
import { getVectorContext } from 'ol/render';
import type RenderEvent from 'ol/render/Event';
import CircleStyle from 'ol/style/Circle';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  FeatureComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  SourceTileWMTSComponent,
  SourceVectorComponent,
  StyleCircleComponent,
  StyleComponent,
  StyleFillComponent,
  StyleIconComponent,
  StyleStrokeComponent,
  TileGridWMTSComponent,
  ViewComponent,
} from 'cc-openlayers';

const size = getWidth(EXTENT) / 256;

/** The marker's look while it is drawn by the animation. */
const markerStyle = new Style({
  image: new CircleStyle({
    radius: 7,
    fill: new Fill({ color: 'black' }),
    stroke: new Stroke({ color: 'white', width: 2 }),
  }),
});

/** The route and the features on it: the marker's position is changed while the animation runs. */
export interface Track {
  line: LineString;
  position: Point;
  start: Point;
  end: Point;
}

/** A marker moving along a route from Rynek Główny to Nowa Huta, drawn with the layer's postrender events at a speed set by a slider. */
@Component({
  selector: 'app-feature-move-animation',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    FeatureComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    SourceTileWMTSComponent,
    SourceVectorComponent,
    StyleCircleComponent,
    StyleComponent,
    StyleFillComponent,
    StyleIconComponent,
    StyleStrokeComponent,
    TileGridWMTSComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="12" [minZoom]="2" [maxZoom]="19">
        <aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile>
        <aol-source-tilewmts
          attributions='Tiles © <a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>'
          url="https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution"
          layer="ORTOFOTOMAPA"
          matrixSet="EPSG:3857"
          format="image/jpeg"
          projection="EPSG:3857"
          [style]="'default'"
        >
          <aol-tilegrid-wmts [origin]="origin" [resolutions]="resolutions" [matrixIds]="matrixIds" />
        </aol-source-tilewmts>
      </aol-layer-tile>
      <aol-layer-vector [postrender]="animating() ? move : undefined">
        <aol-source-vector
          attributions='Route © <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
        >
          @if (track(); as track) {
            <aol-feature [geometry]="track.line">
              <aol-style><aol-style-stroke [width]="6" [color]="[237, 212, 0, 0.8]" /></aol-style>
            </aol-feature>
            <!-- The marker is hidden while the animation draws it and shown where it stopped. -->
            <aol-feature [geometry]="animating() ? undefined : track.position">
              <aol-style>
                <aol-style-circle [radius]="7">
                  <aol-style-fill color="black" />
                  <aol-style-stroke color="white" [width]="2" />
                </aol-style-circle>
              </aol-style>
            </aol-feature>
            <aol-feature [geometry]="track.start">
              <aol-style><aol-style-icon src="assets/marker.svg" [anchor]="[0.5, 1]" [scale]="2" /></aol-style>
            </aol-feature>
            <aol-feature [geometry]="track.end">
              <aol-style><aol-style-icon src="assets/marker.svg" [anchor]="[0.5, 1]" [scale]="2" /></aol-style>
            </aol-feature>
          }
        </aol-source-vector>
      </aol-layer-vector>
    </aol-map>
    <div class="example-controls">
      <label>
        Speed
        <input type="range" min="10" max="999" step="10" [value]="speed()" (input)="speed.set(number($event))" />
        <output>{{ speed() }}</output>
      </label>
      <button type="button" (click)="toggle()">{{ animating() ? 'Stop Animation' : 'Start Animation' }}</button>
    </div>
  `,
})
export class FeatureMoveAnimation {
  readonly speed = signal(60);
  readonly animating = signal(false);
  readonly track = signal<Track | null>(null);
  protected readonly origin = getTopLeft(EXTENT);
  protected readonly resolutions = Array.from({ length: 20 }, (_, z) => size / 2 ** z);
  protected readonly matrixIds = Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`);
  private readonly map = viewChild.required(MapComponent);
  /** How far along the route and back the marker is: 0 to 1 is out, 1 to 2 is the way back. */
  private readonly distance = signal(0);
  private readonly lastTime = signal(0);

  constructor() {
    void this.loadRoute();
  }

  protected number(event: Event): number {
    return (event.target as HTMLInputElement).valueAsNumber;
  }

  protected toggle(): void {
    this.lastTime.set(Date.now());
    this.animating.update((animating) => !animating);
  }

  /** Moves the marker to where it should be at the time of the frame, draws it and asks for the next frame. */
  protected readonly move = (event: RenderEvent): void => {
    const track = this.track();
    if (!track || !event.frameState) return;
    const time = event.frameState.time;
    const distance = (this.distance() + (this.speed() * (time - this.lastTime())) / 1e6) % 2;
    this.distance.set(distance);
    this.lastTime.set(time);
    track.position.setCoordinates(track.line.getCoordinateAt(distance > 1 ? 2 - distance : distance));
    const vectorContext = getVectorContext(event);
    vectorContext.setStyle(markerStyle);
    vectorContext.drawGeometry(track.position);
    this.map().instance.render();
  };

  /** The route is the encoded polyline of a directions service's answer (OSRM, over OpenStreetMap's streets). */
  private async loadRoute(): Promise<void> {
    const response = await fetch('assets/feature-move-animation/route.json');
    const result = (await response.json()) as { routes: { geometry: string }[] };
    const line = new Polyline({ factor: 1e6 }).readGeometry(result.routes[0].geometry, {
      dataProjection: 'EPSG:4326',
      featureProjection: 'EPSG:3857',
    }) as LineString;
    this.track.set({
      line,
      position: new Point(line.getFirstCoordinate()),
      start: new Point(line.getFirstCoordinate()),
      end: new Point(line.getLastCoordinate()),
    });
  }
}

Architecture and OpenLayers mechanics

new Polyline({ factor: 1e6 }) decodes a 6-decimal precision routing string into the route geometry. Conditional [postrender]="animating() ? move : undefined" attaches the frame loop strictly while running.

Inside move, elapsed milliseconds since lastTime advance distance between 0 and 2 (outbound 0..1, return 1..2), sampling exact route coordinates via getCoordinateAt(distance > 1 ? 2 - distance : distance). While moving, the static marker feature hides its geometry (animating() ? undefined : track.position) and reappears at the stopped coordinate when paused.

How it works

  • new Polyline({ factor: 1e6 }) decodes six-decimal-place encoded polylines from routing engines (overriding the 5-decimal default).
  • [postrender]="animating() ? move : undefined" attaches the per-frame listener strictly while playback is active.
  • move integrates elapsed frame time (lastTime) across 0..2 and samples outbound/return positions via getCoordinateAt(distance > 1 ? 2 - distance : distance).
  • Setting marker feature geometry to animating() ? undefined : track.position hands off seamlessly between transient postrender frames and static paused state.

Pitfalls

  • Always advance progress by elapsed milliseconds (frameState.time - lastTime) rather than adding a fixed constant per frame—otherwise 120 Hz ProMotion displays run the vehicle twice as fast as 60 Hz monitors.
  • Here speed is progress per 1000 seconds (speed / 1e6 per millisecond) rather than physical m/s, so travel duration stays constant regardless of total route length unless normalised by route.getLength().
  • While animating() is true, the moving dot is painted transiently on canvas and is not returned by forEachFeatureAtPixel until paused.

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.