Interactions · Angular, React and OpenLayers

Measure with labels drawn as styles

Measure spherical distances and areas in OpenLayers using vector Text styles for totals, per-segment lengths and live cursor guidance tips.

A map of the Old Town with a line measured from the Barbican past the Main Square down Grodzka Street, its segments labelled 0.53, 0.36 and 0.29 km and 1.17 km in all.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Sketching a route from the Barbican past Kraków’s Main Square down Grodzka Street—or enclosing a polygon—renders both the total spherical distance/area badge and optional individual segment lengths (0.53 km, 0.36 km, 0.29 km) directly as canvas vector styles alongside a cursor prompt that resets when the sketch finishes, while a separate Drag to modify hint appears at the last vertex.

When you need it

Traditional HTML overlay measurement tools accumulate dozens of floating DOM badges that must be manually repositioned on vertex edits and cleaned up separately when features are deleted.

Drawing measurement callouts inside the vector style function itself guarantees every segment label and total automatically moves when vertices are dragged and vanishes the instant the feature is cleared.

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.

measure-style.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  SourceOsmComponent,
  SourceVectorComponent,
  ViewComponent,
} from 'cc-openlayers';
import { DrawInteractionComponent, ModifyInteractionComponent } from 'cc-openlayers/editing';
import type Feature from 'ol/Feature';
import type Geometry from 'ol/geom/Geometry';
import LineString from 'ol/geom/LineString';
import type Polygon from 'ol/geom/Polygon';
import Point from 'ol/geom/Point';
import { getArea, getLength } from 'ol/sphere';
import CircleStyle from 'ol/style/Circle';
import Fill from 'ol/style/Fill';
import RegularShape from 'ol/style/RegularShape';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import Text from 'ol/style/Text';

type MeasureType = 'LineString' | 'Polygon';

const white = new Fill({ color: 'rgba(255, 255, 255, 1)' });
const dim = (alpha: number) => new Fill({ color: `rgba(0, 0, 0, ${alpha})` });

const style = new Style({
  fill: new Fill({ color: 'rgba(255, 255, 255, 0.2)' }),
  stroke: new Stroke({ color: 'rgba(0, 0, 0, 0.5)', lineDash: [10, 10], width: 2 }),
  image: new CircleStyle({
    radius: 5,
    stroke: new Stroke({ color: 'rgba(0, 0, 0, 0.7)' }),
    fill: new Fill({ color: 'rgba(255, 255, 255, 0.2)' }),
  }),
});

const labelStyle = new Style({
  text: new Text({
    font: '14px Calibri,sans-serif',
    fill: white,
    backgroundFill: dim(0.7),
    padding: [3, 3, 3, 3],
    textBaseline: 'bottom',
    offsetY: -15,
  }),
  image: new RegularShape({ radius: 8, points: 3, angle: Math.PI, displacement: [0, 10], fill: dim(0.7) }),
});

const tipStyle = new Style({
  text: new Text({
    font: '12px Calibri,sans-serif',
    fill: white,
    backgroundFill: dim(0.4),
    padding: [2, 2, 2, 2],
    textAlign: 'left',
    offsetX: 15,
  }),
});

const modifyStyle = new Style({
  image: new CircleStyle({
    radius: 5,
    stroke: new Stroke({ color: 'rgba(0, 0, 0, 0.7)' }),
    fill: dim(0.4),
  }),
  text: new Text({
    text: 'Drag to modify',
    font: '12px Calibri,sans-serif',
    fill: white,
    backgroundFill: dim(0.7),
    padding: [2, 2, 2, 2],
    textAlign: 'left',
    offsetX: 15,
  }),
});

const segmentStyle = new Style({
  text: new Text({
    font: '12px Calibri,sans-serif',
    fill: white,
    backgroundFill: dim(0.4),
    padding: [2, 2, 2, 2],
    textBaseline: 'bottom',
    offsetY: -12,
  }),
  image: new RegularShape({ radius: 6, points: 3, angle: Math.PI, displacement: [0, 8], fill: dim(0.4) }),
});

/** One style per segment label, grown as the longest measured line needs. */
const segmentStyles = [segmentStyle];

function formatLength(line: LineString): string {
  const length = getLength(line);
  return length > 100 ? `${Math.round((length / 1000) * 100) / 100} km` : `${Math.round(length * 100) / 100} m`;
}

function formatArea(polygon: Polygon): string {
  const area = getArea(polygon);
  return area > 10000 ? `${Math.round((area / 1000000) * 100) / 100} km\xB2` : `${Math.round(area * 100) / 100} m\xB2`;
}

/** Lengths and areas measured with vector styles: the figure, optional segment lengths and a tip near the pointer. */
@Component({
  selector: 'app-measure-style',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    DrawInteractionComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    ModifyInteractionComponent,
    SourceOsmComponent,
    SourceVectorComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="15">
        <aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
      <aol-layer-vector [style]="layerStyle">
        <aol-source-vector #source />
      </aol-layer-vector>
      <aol-interaction-modify #modify [source]="source.instance" [style]="modifyStyle" />
      <!-- A new interaction for each type, as the draw interaction takes its type once. -->
      @switch (type()) {
        @case ('LineString') {
          <aol-interaction-draw
            type="LineString"
            [source]="source.instance"
            [style]="drawStyle"
            (drawStart)="drawStart()"
            (drawEnd)="drawEnd()"
          />
        }
        @case ('Polygon') {
          <aol-interaction-draw
            type="Polygon"
            [source]="source.instance"
            [style]="drawStyle"
            (drawStart)="drawStart()"
            (drawEnd)="drawEnd()"
          />
        }
      }
    </aol-map>
    <div class="example-controls">
      <label>
        Measurement type
        <select [value]="type()" (change)="type.set(measureType($event))">
          <option value="LineString">Length (LineString)</option>
          <option value="Polygon">Area (Polygon)</option>
        </select>
      </label>
      <label>
        Show segment lengths
        <input type="checkbox" [checked]="segments()" (change)="showSegments($event)" />
      </label>
      <label>
        Clear previous measure
        <input type="checkbox" [checked]="clearPrevious()" (change)="clearPrevious.set(checked($event))" />
      </label>
    </div>
  `,
})
export class MeasureStyle {
  readonly type = signal<MeasureType>('LineString');
  readonly segments = signal(true);
  readonly clearPrevious = signal(true);
  protected readonly modifyStyle = modifyStyle;
  private readonly tip = signal('Click to start measuring');
  private readonly tipPoint = signal<Geometry | undefined>(undefined);
  private readonly map = viewChild.required(MapComponent);
  private readonly layer = viewChild.required(LayerVectorComponent);
  private readonly source = viewChild.required(SourceVectorComponent);
  private readonly modify = viewChild.required(ModifyInteractionComponent);
  private readonly draw = viewChild(DrawInteractionComponent);

  protected readonly layerStyle = (feature: Feature): Style[] => this.styleFunction(feature, this.segments());
  protected readonly drawStyle = (feature: Feature): Style[] =>
    this.styleFunction(feature, this.segments(), this.type(), this.tip());

  protected drawStart(): void {
    if (this.clearPrevious()) this.source().instance.clear();
    this.modify().instance.setActive(false);
    this.tip.set(`Click to continue drawing the ${this.type() === 'Polygon' ? 'polygon' : 'line'}`);
  }

  protected drawEnd(): void {
    modifyStyle.setGeometry(this.tipPoint());
    this.modify().instance.setActive(true);
    this.map().instance.once('pointermove', () => modifyStyle.setGeometry(undefined));
    this.tip.set('Click to start measuring');
  }

  protected showSegments(event: Event): void {
    this.segments.set(this.checked(event));
    this.layer().instance.changed();
    this.draw()?.instance.getOverlay().changed();
  }

  protected checked(event: Event): boolean {
    return (event.target as HTMLInputElement).checked;
  }

  protected measureType(event: Event): MeasureType {
    return (event.target as HTMLSelectElement).value as MeasureType;
  }

  private styleFunction(feature: Feature, segments: boolean, drawType?: MeasureType, tip?: string): Style[] {
    const styles: Style[] = [];
    const geometry = feature.getGeometry() as Geometry;
    const type = geometry.getType();
    let point: Point | undefined;
    let label: string | undefined;
    let line: LineString | undefined;
    if (!drawType || drawType === type || type === 'Point') {
      styles.push(style);
      if (type === 'Polygon') {
        const polygon = geometry as Polygon;
        point = polygon.getInteriorPoint();
        label = formatArea(polygon);
        line = new LineString(polygon.getCoordinates()[0]);
      } else if (type === 'LineString') {
        line = geometry as LineString;
        point = new Point(line.getLastCoordinate());
        label = formatLength(line);
      }
    }
    if (segments && line) {
      let count = 0;
      line.forEachSegment((a, b) => {
        const segment = new LineString([a, b]);
        if (segmentStyles.length - 1 < count) segmentStyles.push(segmentStyle.clone());
        segmentStyles[count].setGeometry(new Point(segment.getCoordinateAt(0.5)));
        segmentStyles[count].getText()?.setText(formatLength(segment));
        styles.push(segmentStyles[count]);
        count++;
      });
    }
    if (label) {
      labelStyle.setGeometry(point);
      labelStyle.getText()?.setText(label);
      styles.push(labelStyle);
    }
    if (tip && type === 'Point' && !this.modify().instance.getOverlay().getSource()?.getFeatures().length) {
      this.tipPoint.set(geometry);
      tipStyle.getText()?.setText(tip);
      styles.push(tipStyle);
    }
    return styles;
  }
}

Architecture and OpenLayers mechanics

Spherical helpers getLength and getArea from ol/sphere compute great-circle lengths and areas rather than inflated Web Mercator projection units. A unified style function returns the dashed geometry stroke, the total badge anchored at the final line vertex or polygon interior point, and—while Show segment lengths is enabled—a callout at every segment midpoint.

Draw’s sketch style appends the live cursor instruction tip, drawStart and drawEnd coordinate Modify toggling and optional Clear previous measure cleanup, and calling changed repaints both the layer and active sketch whenever display checkboxes toggle.

How it works

  • getLength and getArea compute accurate spherical measurements along great circles instead of distorted Web Mercator units.
  • The vector style function draws the dashed geometry, the total badge and optional per-segment length labels in a single pass.
  • drawStart clears earlier shapes when Clear previous measure is checked and updates the cursor prompt, while drawEnd re-enables Modify editing.
  • Modify’s style displays a Drag to modify hint at the endpoint until the pointer next moves.

Pitfalls

  • Calling planar .getLength() directly on a Web Mercator LineString in Kraków overstates true ground distance by more than 50%—always pass geometries through getLength and getArea from ol/sphere.
  • Toggling external UI checkboxes does not automatically invalidate cached layer rendering—invoke changed on the layer (and sketch overlay) so segment labels appear or disappear immediately.

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.