Vector data · Angular, React and OpenLayers
Waypoints, a route and a track from GPX
Load GPS waypoints, planned routes and recorded tracks from a GPX file in OpenLayers, styling each geometry type over aerial orthophotography.

What this example shows
Over Kraków’s Old Town, the Vistula river and Podgórze on national aerial orthophotography, a single GPX file renders three distinct GPS primitives at once: named sightseeing waypoints as yellow circles, a planned walking route from the Barbican to Wawel in red, and a recorded single-segment track across the river in green, showing feature descriptions below the map on hover or click.
When you need it
Outdoor hiking portals, cycling trackers, field-survey loggers and fleet replay tools import .gpx GPS Exchange Format files containing planned itineraries alongside actual recorded breadcrumb trails.
Styling waypoints, routes and tracks distinctly on one layer lets users compare planned corridors against real field paths 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.
gpx.tsimport { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceTileWMTSComponent,
SourceVectorComponent,
TileGridWMTSComponent,
ViewComponent,
} from 'cc-openlayers';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import { getTopLeft, getWidth } from 'ol/extent';
import GPX from 'ol/format/GPX';
import { EXTENT } from 'ol/proj/epsg3857';
import CircleStyle from 'ol/style/Circle';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
const size = getWidth(EXTENT) / 256;
const styles: Record<string, Style> = {
Point: new Style({
image: new CircleStyle({
fill: new Fill({ color: 'rgba(255,255,0,0.4)' }),
radius: 5,
stroke: new Stroke({ color: '#ff0', width: 1 }),
}),
}),
LineString: new Style({ stroke: new Stroke({ color: '#f00', width: 3 }) }),
MultiLineString: new Style({ stroke: new Stroke({ color: '#0f0', width: 3 }) }),
};
/** A GPX file with waypoints, a route and a track around Kraków's Old Town, over the national orthophoto; features are described on hover and click. */
@Component({
selector: 'app-gpx',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceTileWMTSComponent,
SourceVectorComponent,
TileGridWMTSComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px" (pointerMove)="show($event)" (olClick)="show($event)">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="14"><aol-coordinate [x]="19.9416" [y]="50.0548" 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'"
[wrapX]="true"
>
<aol-tilegrid-wmts [origin]="origin" [resolutions]="resolutions" [matrixIds]="matrixIds" />
</aol-source-tilewmts>
</aol-layer-tile>
<aol-layer-vector [style]="style">
<aol-source-vector
url="assets/samples/sample-route.gpx"
[format]="format"
attributions='Walks © <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
/>
</aol-layer-vector>
</aol-map>
<div class="example-controls">
<span>
Feature <output>{{ info() }}</output>
</span>
</div>
`,
})
export class Gpx {
readonly info = signal('–');
protected readonly format = new GPX();
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}`);
protected readonly style = (feature: { getGeometry(): { getType(): string } | undefined }): Style | undefined =>
styles[feature.getGeometry()?.getType() ?? ''];
private readonly map = viewChild.required(MapComponent);
protected show(event: MapBrowserEvent): void {
if (event.dragging) return;
const map = this.map().instance;
const descriptions: string[] = [];
map.forEachFeatureAtPixel(event.pixel, (feature) => {
descriptions.push(feature.get('desc'));
});
this.info.set(descriptions.length ? descriptions.join(', ') || '(unknown)' : '–');
map.getTargetElement().style.cursor = descriptions.length ? 'pointer' : '';
}
} 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.
gpx.react.tsximport { useRef, useState } from 'react';
import type OLMap from 'ol/Map.js';
import type MapBrowserEvent from 'ol/MapBrowserEvent.js';
import { getTopLeft, getWidth } from 'ol/extent.js';
import GPX from 'ol/format/GPX.js';
import { EXTENT } from 'ol/proj/epsg3857.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 {
Coordinate,
DefaultControls,
DefaultInteractions,
Map,
TileLayer,
VectorLayer,
VectorSource,
View,
WMTSSource,
useWMTSTileGrid,
} from 'cc-openlayers/react';
const size = getWidth(EXTENT) / 256;
const gridOptions = {
origin: getTopLeft(EXTENT),
resolutions: Array.from({ length: 20 }, (_, z) => size / 2 ** z),
matrixIds: Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`),
};
const styles: Record<string, Style> = {
Point: new Style({
image: new CircleStyle({
fill: new Fill({ color: 'rgba(255,255,0,0.4)' }),
radius: 5,
stroke: new Stroke({ color: '#ff0', width: 1 }),
}),
}),
LineString: new Style({ stroke: new Stroke({ color: '#f00', width: 3 }) }),
MultiLineString: new Style({ stroke: new Stroke({ color: '#0f0', width: 3 }) }),
};
const format = new GPX();
const style = (feature: { getGeometry(): { getType(): string } | undefined }): Style | undefined =>
styles[feature.getGeometry()?.getType() ?? ''];
/** A GPX file with waypoints, a route and a track around Kraków's Old Town, over the national orthophoto; features are described on hover and click. */
export function Gpx() {
const [info, setInfo] = useState('–');
const map = useRef<OLMap>(null);
const tileGrid = useWMTSTileGrid(gridOptions);
const show = (event: MapBrowserEvent) => {
if (event.dragging) return;
const current = map.current;
if (!current) return;
const descriptions: string[] = [];
current.forEachFeatureAtPixel(event.pixel, (feature) => {
descriptions.push(feature.get('desc'));
});
setInfo(descriptions.length ? descriptions.join(', ') || '(unknown)' : '–');
(current.getTargetElement() as HTMLElement).style.cursor = descriptions.length ? 'pointer' : '';
};
return (
<>
<Map ref={map} height="480px" onPointerMove={show} onClick={show}>
<DefaultInteractions />
<DefaultControls />
<View zoom={14}>
<Coordinate x={19.9416} y={50.0548} 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"
wrapX={true}
tileGrid={tileGrid}
/>
</TileLayer>
<VectorLayer style={style}>
<VectorSource
url="assets/samples/sample-route.gpx"
format={format}
attributions='Walks © <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
/>
</VectorLayer>
</Map>
<div className="example-controls">
<span>
Feature <output>{info}</output>
</span>
</div>
</>
);
}How the React version works
A GPX file with waypoints, a route and a track around the Old Town over the orthophoto, styled by geometry type, with the features described under the pointer.
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.
From Angular to React
| Angular | React |
|---|---|
<aol-layer-vector> with <aol-source-vector [url] [format]> | <VectorLayer> with <VectorSource url format>; the format is a module constant |
the layer's [style] | the layer's style: a function or a flat style, constant in the module |
<aol-source-tilewmts> with <aol-tilegrid-wmts> | <WMTSSource> with a grid from useWMTSTileGrid |
(pointerMove) and viewChild of the map | onPointerMove (and onClick) on Map with useRef<OLMap>; the reading in useState |
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.
Architecture and OpenLayers mechanics
OpenLayers’ GPX format maps <wpt> elements to Point geometries, <rte> elements to LineString geometries, and <trk> elements—which GPX organises into <trkseg> segments—to MultiLineString geometries. The vector layer’s style function looks up feature.getGeometry().getType() inside a styles dictionary keyed by Point, LineString and MultiLineString, while pointer hover and click collect every hit feature’s desc text.
How it works
GPXdecodes waypoints asPoint, planned routes asLineStringand recorded tracks asMultiLineString(one line per track segment).- A geometry-type lookup in
stylesassigns distinct symbols toPoint,LineStringandMultiLineStringfeatures. - Hovering or clicking displays the
descattribute of every feature under the pointer—listing both a waypoint and a route where they coincide.
Pitfalls
- Even a single-segment GPX <trk> decodes as a
MultiLineString, never aLineString: forgetting aMultiLineStringentry in your style map leaves recorded GPS tracks completely invisible. - Thin 3-pixel route lines are tricky to tap accurately on mobile touch screens unless you pass a pixel hitTolerance to
forEachFeatureAtPixel.
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.