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.

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.tsimport { 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;
}
} 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.
measure-style.react.tsximport { useCallback, useRef, useState } from 'react';
import type { FeatureLike } from 'ol/Feature.js';
import type OLMap from 'ol/Map.js';
import type Geometry from 'ol/geom/Geometry.js';
import LineString from 'ol/geom/LineString.js';
import type Polygon from 'ol/geom/Polygon.js';
import Point from 'ol/geom/Point.js';
import type Draw from 'ol/interaction/Draw.js';
import type Modify from 'ol/interaction/Modify.js';
import type OLVectorLayer from 'ol/layer/Vector.js';
import type OLVectorSource from 'ol/source/Vector.js';
import { getArea, getLength } from 'ol/sphere.js';
import CircleStyle from 'ol/style/Circle.js';
import Fill from 'ol/style/Fill.js';
import RegularShape from 'ol/style/RegularShape.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';
import Text from 'ol/style/Text.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
DrawInteraction,
Map,
ModifyInteraction,
OSMSource,
TileLayer,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
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. */
export function MeasureStyle() {
const [type, setType] = useState<MeasureType>('LineString');
const [segments, setSegments] = useState(true);
const [clearPrevious, setClearPrevious] = useState(true);
const [source, setSource] = useState<OLVectorSource | null>(null);
const map = useRef<OLMap>(null);
const layer = useRef<OLVectorLayer>(null);
const modify = useRef<Modify>(null);
const draw = useRef<Draw>(null);
// The style functions and the draw callbacks are handed to OpenLayers once, so they read what changes
// (the checkboxes, the type, the tip) from these refs, which the handlers below keep up to date.
const segmentsNow = useRef(true);
const typeNow = useRef<MeasureType>('LineString');
const tip = useRef('Click to start measuring');
const tipPoint = useRef<Geometry | null>(null);
const styleFunction = useCallback((feature: FeatureLike, segments: boolean, drawType?: MeasureType, tip?: string) => {
const styles: Style[] = [];
const geometry = feature.getGeometry() as Geometry;
const type = geometry.getType();
let point: Point | null = null;
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' && !modify.current?.getOverlay().getSource()?.getFeatures().length) {
tipPoint.current = geometry;
tipStyle.getText()?.setText(tip);
styles.push(tipStyle);
}
return styles;
}, []);
const layerStyle = useCallback(
(feature: FeatureLike): Style[] => styleFunction(feature, segmentsNow.current),
[styleFunction]
);
const drawStyle = useCallback(
(feature: FeatureLike): Style[] => styleFunction(feature, segmentsNow.current, typeNow.current, tip.current),
[styleFunction]
);
const drawStart = () => {
if (clearPrevious) source?.clear();
modify.current?.setActive(false);
tip.current = `Click to continue drawing the ${typeNow.current === 'Polygon' ? 'polygon' : 'line'}`;
};
const drawEnd = () => {
modifyStyle.setGeometry(tipPoint.current);
modify.current?.setActive(true);
map.current?.once('pointermove', () => modifyStyle.setGeometry(null));
tip.current = 'Click to start measuring';
};
const showSegments = (checked: boolean) => {
segmentsNow.current = checked;
setSegments(checked);
layer.current?.changed();
draw.current?.getOverlay().changed();
};
const chooseType = (next: MeasureType) => {
typeNow.current = next;
setType(next);
};
return (
<>
<Map ref={map} height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={15}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
<VectorLayer ref={layer} style={layerStyle}>
<VectorSource ref={setSource} />
</VectorLayer>
{source ? (
<>
<ModifyInteraction ref={modify} source={source} style={modifyStyle} />
{/* A new interaction for each type, as the draw interaction takes its type once. */}
<DrawInteraction
ref={draw}
type={type}
source={source}
style={drawStyle}
onDrawStart={drawStart}
onDrawEnd={drawEnd}
/>
</>
) : null}
</Map>
<div className="example-controls">
<label>
Measurement type
<select value={type} onChange={(event) => chooseType(event.target.value as MeasureType)}>
<option value="LineString">Length (LineString)</option>
<option value="Polygon">Area (Polygon)</option>
</select>
</label>
<label>
Show segment lengths
<input type="checkbox" checked={segments} onChange={(event) => showSegments(event.target.checked)} />
</label>
<label>
Clear previous measure
<input type="checkbox" checked={clearPrevious} onChange={(event) => setClearPrevious(event.target.checked)} />
</label>
</div>
</>
);
}How the React version works
Lengths and areas measured with vector styles: the figure, optional segment lengths and a tip near the pointer that tells what to do next; modifying is off while drawing.
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-interaction-draw> and <aol-interaction-modify> with style functions reading signals | one <DrawInteraction> (its type prop replaces the interaction) and <ModifyInteraction>; the style functions read the type, the segments switch and the tip from useRef, so they stay stable while the form changes |
(drawStart) and (drawEnd) | onDrawStart and onDrawEnd |
viewChild of the map, layer, draw and modify | useRef for each, and ref={setSource} for the source |
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
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
getLengthandgetAreacompute 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.
drawStartclears earlier shapes when Clear previous measure is checked and updates the cursor prompt, whiledrawEndre-enables Modify editing.- Modify’s style displays a
Drag to modifyhint 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
getLengthandgetAreafromol/sphere. - Toggling external UI checkboxes does not automatically invalidate cached layer rendering—invoke
changedon the layer (and sketch overlay) so segment labels appear or disappear immediately.
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.