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.

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.tsimport { 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()),
});
}
} 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.
feature-move-animation.react.tsximport { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
import Polyline from 'ol/format/Polyline.js';
import type LineString from 'ol/geom/LineString.js';
import Point from 'ol/geom/Point.js';
import { getTopLeft, getWidth } from 'ol/extent.js';
import type OLMap from 'ol/Map.js';
import { EXTENT } from 'ol/proj/epsg3857.js';
import { getVectorContext } from 'ol/render.js';
import type RenderEvent from 'ol/render/Event.js';
import CircleStyle from 'ol/style/Circle.js';
import Fill from 'ol/style/Fill.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';
import {
CircleStyle as CircleStyleDeclaration,
Coordinate,
DefaultControls,
DefaultInteractions,
Feature,
Fill as FillDeclaration,
IconStyle,
Map,
Stroke as StrokeDeclaration,
Style as StyleDeclaration,
TileLayer,
VectorLayer,
VectorSource,
View,
WMTSSource,
useWMTSTileGrid,
} from 'cc-openlayers/react';
const size = getWidth(EXTENT) / 256;
const origin = getTopLeft(EXTENT);
const resolutions = Array.from({ length: 20 }, (_, z) => size / 2 ** z);
const matrixIds = Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`);
const routeColor = [237, 212, 0, 0.8];
const markerAnchor = [0.5, 1];
/** 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;
}
/** The route is the encoded polyline of a directions service's answer (OSRM, over OpenStreetMap's streets). */
async function loadRoute(): Promise<Track> {
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;
return {
line,
position: new Point(line.getFirstCoordinate()),
start: new Point(line.getFirstCoordinate()),
end: new Point(line.getLastCoordinate()),
};
}
/** 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. */
export function FeatureMoveAnimation() {
const [speed, setSpeed] = useState(60);
const [animating, setAnimating] = useState(false);
const [track, setTrack] = useState<Track | null>(null);
const map = useRef<OLMap>(null);
/** How far along the route and back the marker is: 0 to 1 is out, 1 to 2 is the way back. */
const distance = useRef(0);
const lastTime = useRef(0);
const tileGrid = useWMTSTileGrid({ origin, resolutions, matrixIds });
useEffect(() => {
let current = true;
void loadRoute().then((loaded) => {
if (current) setTrack(loaded);
});
return () => {
current = false;
};
}, []);
const toggle = () => {
lastTime.current = Date.now();
setAnimating(!animating);
};
/** Moves the marker to where it should be at the time of the frame, draws it and asks for the next frame. */
const move = useCallback(
(event: RenderEvent) => {
if (!track || !event.frameState) return;
const time = event.frameState.time;
distance.current = (distance.current + (speed * (time - lastTime.current)) / 1e6) % 2;
lastTime.current = time;
track.position.setCoordinates(
track.line.getCoordinateAt(distance.current > 1 ? 2 - distance.current : distance.current)
);
const vectorContext = getVectorContext(event);
vectorContext.setStyle(markerStyle);
vectorContext.drawGeometry(track.position);
map.current?.render();
},
[track, speed]
);
return (
<>
<Map ref={map} height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={12} minZoom={2} maxZoom={19}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<WMTSSource
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"
tileGrid={tileGrid}
/>
</TileLayer>
<VectorLayer onPostRender={animating ? move : undefined}>
<VectorSource attributions='Route © <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'>
{track ? (
<>
<Feature geometry={track.line}>
<StyleDeclaration>
<StrokeDeclaration width={6} color={routeColor} />
</StyleDeclaration>
</Feature>
{/* The marker is hidden while the animation draws it and shown where it stopped. */}
<Feature geometry={animating ? undefined : track.position}>
<StyleDeclaration>
<CircleStyleDeclaration radius={7}>
<FillDeclaration color="black" />
<StrokeDeclaration color="white" width={2} />
</CircleStyleDeclaration>
</StyleDeclaration>
</Feature>
<Feature geometry={track.start}>
<StyleDeclaration>
<IconStyle src="assets/marker.svg" anchor={markerAnchor} scale={2} />
</StyleDeclaration>
</Feature>
<Feature geometry={track.end}>
<StyleDeclaration>
<IconStyle src="assets/marker.svg" anchor={markerAnchor} scale={2} />
</StyleDeclaration>
</Feature>
</>
) : null}
</VectorSource>
</VectorLayer>
</Map>
<div className="example-controls">
<label>
Speed
<input
type="range"
min="10"
max="999"
step="10"
value={speed}
onChange={(event: ChangeEvent<HTMLInputElement>) => setSpeed(event.target.valueAsNumber)}
/>
<output>{speed}</output>
</label>
<button type="button" onClick={toggle}>
{animating ? 'Stop Animation' : 'Start Animation'}
</button>
</div>
</>
);
}How the React version works
A marker rides a route from the Main Square to Nowa Huta and back; a slider sets the speed and a button starts and stops the animation. While it runs, the vector layer's postrender event draws the marker, and after a stop it stays where it stopped.
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. Both versions compute the WMTS tile grid of GUGiK's orthophoto (origin, 20 resolutions, ids EPSG:3857:z) in the same way; in React the useWMTSTileGrid hook creates it once from module constants. The route is a polyline from an OSRM answer in assets/feature-move-animation/route.json, read with ol/format/Polyline.
From Angular to React
| Angular | React |
|---|---|
signal for the speed and the animation state | useState |
the class fields distance and lastTime | useRef, because they change every frame and must not render |
[postrender]="animating() ? move : undefined" | onPostRender={animating ? move : undefined} |
<aol-style> with <aol-style-circle>, <aol-style-icon> | <Style> with <CircleStyle>, <IconStyle> (Style, CircleStyle, Fill and Stroke under aliases ending in Declaration, because the ol/style classes take those names) |
<aol-source-tilewmts> with <aol-tilegrid-wmts> inside | <WMTSSource tileGrid={tileGrid}> with useWMTSTileGrid(...) |
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 route lives in an effect with a flag that ignores an answer after unmount.
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.moveintegrates elapsed frame time (lastTime) across 0..2 and samples outbound/return positions viagetCoordinateAt(distance > 1 ? 2 - distance : distance).- Setting marker feature geometry to
animating() ? undefined : track.positionhands off seamlessly between transientpostrenderframes 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
speedis 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.
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.