Vector data · Angular, React and OpenLayers

Place markers along a route

Measure geographic route length and place distance-interval markers along polylines in OpenLayers using @turf/length and @turf/along helpers.

Measure a route and place points at distances along it using Turf.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Along a route over Kraków on OpenStreetMap, geographic chainage markers (km posts / distance intervals) are positioned accurately along the path and linked to an interactive distance control shared across Angular and React.

When you need it

Highway linear referencing (kilometre posts), pipeline inspection stationing, marathon mile markers and hiking-trail elevation callouts all place points at exact geodesic distances measured along a route.

Combining Turf’s modular geodesic helpers (@turf/length and @turf/along) with OpenLayers vector features keeps bundle size minimal and distance math accurate.

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.

turf.html
<aol-map height="480px"
  ><aol-control-defaults /><aol-interaction-default /><aol-view [zoom]="13" [maxZoom]="19"
    ><aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" /></aol-view
  ><aol-layer-tile><aol-source-osm /></aol-layer-tile
></aol-map>
<div class="example-controls">
  <label
    >Distance along route
    <input type="range" min="0" [max]="length" step="0.01" [value]="distance()" (input)="setDistance($event)" /><output
      >{{ distance().toFixed(2) }} km</output
    ></label
  ><span
    >Route length <output>{{ length.toFixed(2) }} km</output></span
  ><span
    >Markers <output>{{ markerCount }}</output></span
  >
</div>
turf.shared.ts
import { along } from '@turf/along';
import { length } from '@turf/length';
import Feature from 'ol/Feature';
import GeoJSON from 'ol/format/GeoJSON';
import Point from 'ol/geom/Point';
import VectorSource from 'ol/source/Vector';
import { fromLonLat } from 'ol/proj';
export const ROUTE = [
  [19.912, 50.059],
  [19.925, 50.06],
  [19.937, 50.0614],
  [19.947, 50.063],
  [19.959, 50.063],
];
const format = new GeoJSON();
function line(coordinates: number[][]) {
  return { type: 'Feature' as const, properties: {}, geometry: { type: 'LineString' as const, coordinates } };
}
export function routeLength(coordinates: number[][]): number {
  return length(line(coordinates), { units: 'kilometers' });
}
export function routePoint(coordinates: number[][], distance: number): Feature<Point> {
  return new Feature(
    new Point(fromLonLat(along(line(coordinates), distance, { units: 'kilometers' }).geometry.coordinates))
  );
}
export function routeMarkers(coordinates: number[][]): VectorSource {
  const features = [format.readFeature(line(coordinates), { featureProjection: 'EPSG:3857' }) as Feature];
  for (let distance = 0.2; distance <= routeLength(coordinates); distance += 0.2)
    features.push(routePoint(coordinates, distance));
  return new VectorSource({ features });
}
turf.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, OnDestroy, signal, viewChild } from '@angular/core';
import {
  MapComponent,
  ViewComponent,
  CoordinateComponent,
  LayerTileComponent,
  SourceOsmComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
} from 'cc-openlayers';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Style from 'ol/style/Style';
import Circle from 'ol/style/Circle';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import { ROUTE, routeLength, routeMarkers, routePoint } from './turf.shared';

@Component({
  selector: 'app-turf',
  imports: [
    MapComponent,
    ViewComponent,
    CoordinateComponent,
    LayerTileComponent,
    SourceOsmComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './turf.html',
})
export class Turf implements AfterViewInit, OnDestroy {
  private readonly map = viewChild.required(MapComponent);
  readonly length = routeLength(ROUTE);
  readonly distance = signal(0);
  private readonly source = routeMarkers(ROUTE);
  readonly markerCount = this.source.getFeatures().length - 1;
  private readonly marker = routePoint(ROUTE, 0);
  private cleanup = () => {};
  ngAfterViewInit(): void {
    const map = this.map().instance,
      layers = [
        new VectorLayer({ source: this.source }),
        new VectorLayer({
          source: new VectorSource({ features: [this.marker] }),
          style: new Style({
            image: new Circle({
              radius: 9,
              fill: new Fill({ color: '#d43' }),
              stroke: new Stroke({ color: '#fff', width: 2 }),
            }),
          }),
        }),
      ];
    layers.forEach((l) => map.addLayer(l));
    this.cleanup = () => layers.forEach((l) => map.removeLayer(l));
  }
  ngOnDestroy(): void {
    this.cleanup();
  }
  setDistance(e: Event): void {
    this.distance.set((e.target as HTMLInputElement).valueAsNumber);
    this.marker.setGeometry(routePoint(ROUTE, this.distance()).getGeometry());
  }
}

Architecture and OpenLayers mechanics

Shared calculation logic takes the route’s RFC 7946 WGS 84 [longitude, latitude] coordinates directly, computes total geodesic route length with @turf/length, interpolates a highlighted marker along the route with @turf/along as the distance control changes, and projects that marker to EPSG:3857 with fromLonLat, while fixed markers sit every 0.2 km along the line on a second vector layer.

How it works

  • Modular helpers @turf/length and @turf/along compute geodesic route length and interpolate marker positions at exact distances along the line.

Pitfalls

  • Turf.js functions strictly assume WGS 84 [longitude, latitude] degree coordinates and explicit unit options (kilometers, meters)—passing raw EPSG:3857 Web Mercator metres directly into Turf produces nonsensical planetary distances.

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.