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.

The orthophoto of Kraków's Old Town and Podgórze with yellow waypoints, a red route from the Barbican to Wawel and a green track over the Vistula to Podgórze, and below the map the descriptions of the Main Square's waypoint and of the route under the pointer.
A screenshot of the example. Orthophotomap © GUGiK. Map data © OpenStreetMap contributors.

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.ts
import { 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' : '';
  }
}

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

  • GPX decodes waypoints as Point, planned routes as LineString and recorded tracks as MultiLineString (one line per track segment).
  • A geometry-type lookup in styles assigns distinct symbols to Point, LineString and MultiLineString features.
  • Hovering or clicking displays the desc attribute 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 a LineString: forgetting a MultiLineString entry 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.

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.