Interactions · Angular, React and OpenLayers
Trace borders while drawing and editing
Trace official PRG municipal borders around Kraków during both initial polygon drawing and subsequent Modify vertex editing in OpenLayers.

What this example shows
Over GUGiK’s aerial orthophotomap with official PRG municipal boundaries in red, you can trace Kraków’s intricate northern border while sketching a new green polygon—and after drawEnd automatically switches the toolbar to Modify only, you can also reshape existing edges onto municipal borders by dragging two neighbouring vertices onto a border.
When you need it
Real-world cadastral and zoning workflows rarely get every shared boundary right during initial sketching; analysts also need existing polygons to conform vertex-for-vertex to reference borders during later edits.
Enabling trace and traceSource on both aol-interaction-draw and aol-interaction-modify unifies initial boundary tracing and post-draw boundary conforming.
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.
draw-modify-trace-snap.tsimport { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
import { getTopLeft, getWidth } from 'ol/extent';
import { EXTENT } from 'ol/proj/epsg3857';
import type { FlatStyle } from 'ol/style/flat';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceGeoJSONComponent,
SourceTileWMTSComponent,
SourceVectorComponent,
TileGridWMTSComponent,
ViewComponent,
} from 'cc-openlayers';
import { DrawInteractionComponent, ModifyInteractionComponent, SnapInteractionComponent } from 'cc-openlayers/editing';
type Mode = 'Polygon' | 'LineString' | 'None';
const size = getWidth(EXTENT) / 256;
/**
* Shapes drawn and modified along the borders of Kraków and the municipalities around it (PRG): a click on a border
* starts tracing it and a second click stops; dragging a vertex onto a border traces the next drag of its neighbour.
*/
@Component({
selector: 'app-draw-modify-trace-snap',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
DrawInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
ModifyInteractionComponent,
SnapInteractionComponent,
SourceGeoJSONComponent,
SourceTileWMTSComponent,
SourceVectorComponent,
TileGridWMTSComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="11" [maxZoom]="23">
<aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
</aol-view>
<aol-layer-tile>
<aol-source-tilewmts
attributions='Tiles © <a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>'
crossOrigin="anonymous"
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'"
>
<aol-tilegrid-wmts [origin]="origin" [resolutions]="resolutions" [matrixIds]="matrixIds" />
</aol-source-tilewmts>
</aol-layer-tile>
<!-- features in this layer will be snapped to -->
<aol-layer-vector [style]="baseStyle">
<aol-source-geojson
#base
url="assets/poland/krakow-municipalities.geojson"
featureProjection="EPSG:3857"
attributions="Boundaries: PRG, GUGiK"
/>
</aol-layer-vector>
<!-- this is where the drawn features go -->
<aol-layer-vector [style]="drawStyle"><aol-source-vector #drawn /></aol-layer-vector>
<aol-interaction-modify [source]="drawn.instance" [trace]="true" [traceSource]="base.instance" />
@if (drawType(); as type) {
<aol-interaction-draw
[type]="type"
[source]="drawn.instance"
[trace]="true"
[traceSource]="base.instance"
[style]="sketchStyle"
(drawEnd)="mode.set('None')"
/>
}
<!-- Snap must come after the interactions whose pointer it moves: it is added anew after every change of mode. -->
@for (current of modes; track current.value) {
@if (current.value === mode()) {
<aol-interaction-snap [source]="base.instance" />
}
}
</aol-map>
<div class="example-controls">
<label>
Draw geometry mode
<select name="mode" (change)="choose($event)">
@for (option of modes; track option.value) {
<option [value]="option.value" [selected]="option.value === mode()">{{ option.label }}</option>
}
</select>
</label>
</div>
`,
})
export class DrawModifyTraceSnap {
/** After a shape is drawn, the mode turns to modifying only. */
readonly mode = signal<Mode>('Polygon');
/** The geometry type drawn in the current mode; none when only modifying. */
protected readonly drawType = computed(() => {
const mode = this.mode();
return mode === 'None' ? undefined : mode;
});
protected readonly modes: { value: Mode; label: string }[] = [
{ value: 'Polygon', label: 'Polygon' },
{ value: 'LineString', label: 'LineString' },
{ value: 'None', label: 'Modify only' },
];
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 baseStyle: FlatStyle = {
'fill-color': 'rgba(255, 0, 0, 0.3)',
'stroke-color': 'rgba(255, 0, 0, 0.9)',
'stroke-width': 0.5,
};
protected readonly drawStyle: FlatStyle = {
'stroke-color': 'rgba(100, 255, 0, 1)',
'stroke-width': 2,
'fill-color': 'rgba(100, 255, 0, 0.3)',
};
protected readonly sketchStyle: FlatStyle = {
'stroke-color': 'rgba(255, 255, 100, 0.5)',
'stroke-width': 1.5,
'fill-color': 'rgba(255, 255, 100, 0.25)',
'circle-radius': 6,
'circle-fill-color': 'rgba(255, 255, 100, 0.5)',
};
protected choose(event: Event): void {
this.mode.set((event.target as HTMLSelectElement).value as Mode);
}
} 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.
draw-modify-trace-snap.react.tsximport { useState } from 'react';
import { getTopLeft, getWidth } from 'ol/extent.js';
import { EXTENT } from 'ol/proj/epsg3857.js';
import type OLVectorSource from 'ol/source/Vector.js';
import type { FlatStyle } from 'ol/style/flat.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
DrawInteraction,
GeoJSONSource,
Map,
ModifyInteraction,
SnapInteraction,
TileLayer,
VectorLayer,
VectorSource,
View,
WMTSSource,
useWMTSTileGrid,
} from 'cc-openlayers/react';
type Mode = 'Polygon' | 'LineString' | 'None';
const size = getWidth(EXTENT) / 256;
const modes: { value: Mode; label: string }[] = [
{ value: 'Polygon', label: 'Polygon' },
{ value: 'LineString', label: 'LineString' },
{ value: 'None', label: 'Modify only' },
];
const gridOptions = {
origin: getTopLeft(EXTENT),
resolutions: Array.from({ length: 20 }, (_, z) => size / 2 ** z),
matrixIds: Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`),
};
const baseStyle: FlatStyle = {
'fill-color': 'rgba(255, 0, 0, 0.3)',
'stroke-color': 'rgba(255, 0, 0, 0.9)',
'stroke-width': 0.5,
};
const drawStyle: FlatStyle = {
'stroke-color': 'rgba(100, 255, 0, 1)',
'stroke-width': 2,
'fill-color': 'rgba(100, 255, 0, 0.3)',
};
const sketchStyle: FlatStyle = {
'stroke-color': 'rgba(255, 255, 100, 0.5)',
'stroke-width': 1.5,
'fill-color': 'rgba(255, 255, 100, 0.25)',
'circle-radius': 6,
'circle-fill-color': 'rgba(255, 255, 100, 0.5)',
};
/**
* Shapes drawn and modified along the borders of Kraków and the municipalities around it (PRG): a click on a border
* starts tracing it and a second click stops; dragging a vertex onto a border traces the next drag of its neighbour.
*/
export function DrawModifyTraceSnap() {
/** After a shape is drawn, the mode turns to modifying only. */
const [mode, setMode] = useState<Mode>('Polygon');
const [base, setBase] = useState<OLVectorSource | null>(null);
const [drawn, setDrawn] = useState<OLVectorSource | null>(null);
const tileGrid = useWMTSTileGrid(gridOptions);
/** The geometry type drawn in the current mode; none when only modifying. */
const drawType = mode === 'None' ? undefined : mode;
return (
<>
<Map height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={11} maxZoom={23}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<WMTSSource
attributions='Tiles © <a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>'
crossOrigin="anonymous"
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"
tileGrid={tileGrid}
/>
</TileLayer>
{/* features in this layer will be snapped to */}
<VectorLayer style={baseStyle}>
<GeoJSONSource
ref={setBase}
url="assets/poland/krakow-municipalities.geojson"
featureProjection="EPSG:3857"
attributions="Boundaries: PRG, GUGiK"
/>
</VectorLayer>
{/* this is where the drawn features go */}
<VectorLayer style={drawStyle}>
<VectorSource ref={setDrawn} />
</VectorLayer>
{base && drawn ? (
<>
<ModifyInteraction source={drawn} trace={true} traceSource={base} />
{drawType ? (
<DrawInteraction
type={drawType}
source={drawn}
trace={true}
traceSource={base}
style={sketchStyle}
onDrawEnd={() => setMode('None')}
/>
) : null}
{/* Snap must come after the interactions whose pointer it moves: it is added anew after every change of mode. */}
<SnapInteraction key={mode} source={base} />
</>
) : null}
</Map>
<div className="example-controls">
<label>
Draw geometry mode
<select name="mode" value={mode} onChange={(event) => setMode(event.target.value as Mode)}>
{modes.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</label>
</div>
</>
);
}How the React version works
Shapes drawn and modified along the borders of Kraków and the municipalities around it (PRG): a click on a border starts tracing it and a second click stops; dragging a vertex onto a border traces the next drag of its neighbour.
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. The snap interaction is rendered after the draw and modify interactions in both versions, because OpenLayers lets the last added interaction handle a pointer event first.
From Angular to React
| Angular | React |
|---|---|
a mode <select> with (change) and a computed | onChange and useState; the draw interaction gets key={mode} |
viewChild of the borders and the drawn sources | ref={setBase} and ref={setDrawn} into useState |
(drawEnd) turning to modifying | onDrawEnd |
<aol-source-tilewmts> with <aol-tilegrid-wmts> inside | <WMTSSource tileGrid={tileGrid}> with useWMTSTileGrid(...) |
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
Both aol-interaction-draw and aol-interaction-modify bind [trace] and [traceSource] to the PRG municipalities vector source. During Draw, two clicks along a border splice all intermediate border vertices; during Modify, dragging one vertex onto a border and then dragging its immediate neighbour onto that same border replaces the straight segment between them with the exact traced border vertices.
On drawEnd the mode switches to Modify only, recreating Snap after each mode transition so pointer snapping always runs first.
How it works
[trace]and[traceSource]onaol-interaction-drawcopy municipal border vertices between two clicks while sketching.- Matching
[trace]and[traceSource]inputs onaol-interaction-modifytrace borders whenever two adjacent vertices are dragged onto the same boundary. - Finishing a polygon (
drawEnd) transitions automatically into Modify-only editing mode. - Recreating Snap on every mode switch keeps Snap registered last so pointer coordinates snap reliably to PRG borders.
Pitfalls
- Omitting
traceSourceon either Draw or Modify causes that interaction to trace only user-drawn shapes rather than the reference municipal boundaries. - Modify tracing activates strictly when you drag a vertex that is an immediate topological neighbour of the previously snapped vertex—dragging a non-adjacent corner moves only that single vertex without tracing.
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.