Interactions · Angular, React and OpenLayers
Edit a connected planar topology
Draw and edit connected planar topology graphs—nodes, shared edges and polygon faces—in OpenLayers using Topolis, edge snapping and cleanup.

What this example shows
Over OpenStreetMap of Kraków, sketching connected LineString edges automatically builds and maintains a live planar topological graph rendered across three coordinated vector layers: junction nodes, directed shared edges and enclosed polygon faces, with snapping onto existing edges.
When you need it
Cadastral parcel subdivision, administrative boundary maintenance and utility network editing require true planar topology—where moving or splitting one shared border updates both adjacent polygons automatically without creating slivers or overlaps.
Integrating topolis (a JavaScript port of PostGIS Topology concepts) with OpenLayers brings node-edge-face topological rules into browser digitising.
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.
topolis-packages.tsdeclare module 'topolis' {
export interface Node {
id: number;
coordinate: number[];
face?: Face;
}
export interface Edge {
id: number;
coordinates: number[][];
start: Node;
end: Node;
}
export interface Face {
id: number;
}
export interface Topology {
on(type: 'addnode' | 'removenode', callback: (node: Node) => void): void;
on(type: 'addedge' | 'modedge' | 'removeedge', callback: (edge: Edge) => void): void;
on(type: 'addface' | 'modface' | 'removeface', callback: (face: Face) => void): void;
getNodeByPoint(coordinate: number[]): Node | undefined;
getEdgeByPoint(coordinate: number[], tolerance: number): Edge[];
getEdgesByLine(coordinates: number[][]): Edge[];
addIsoNode(coordinate: number[]): Node;
removeIsoNode(node: Node): void;
modEdgeSplit(edge: Edge, coordinate: number[]): Node;
addEdgeNewFaces(start: Node, end: Node, coordinates: number[][]): Edge;
remEdgeNewFace(edge: Edge): Face;
getFaceGeometry(face: Face): number[][][];
}
export function createTopology(): Topology;
}topolis.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">
<p class="example-hint">Draw connected edges to form faces. Draw across one edge to remove it.</p>
@if (error()) {
<p role="alert">The edge could not be added.</p>
}
</div>topolis.shared.tsimport './topolis-packages';
import { createTopology } from 'topolis';
import type { Edge, Node, Face } from 'topolis';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import LineString from 'ol/geom/LineString';
import Polygon from 'ol/geom/Polygon';
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 Text from 'ol/style/Text';
import type { FeatureLike } from 'ol/Feature';
import { fromLonLat } from 'ol/proj';
export const topologyStyle = (kind: 'node' | 'edge' | 'face') => (f: FeatureLike) =>
new Style({
image:
kind === 'node'
? new Circle({
radius: 7,
fill: new Fill({ color: 'rgba(230,40,40,.25)' }),
stroke: new Stroke({ color: '#d22', width: 2 }),
})
: undefined,
stroke: new Stroke({ color: kind === 'edge' ? '#27c' : '#151', width: 2 }),
fill: kind === 'face' ? new Fill({ color: 'rgba(30,190,80,.2)' }) : undefined,
text: new Text({
text: String(f.getId()),
fill: new Fill({ color: kind === 'node' ? '#d22' : kind === 'edge' ? '#27c' : '#151' }),
stroke: new Stroke({ color: '#fff', width: 3 }),
}),
});
export function topologyDemo(seed = false) {
const topo = createTopology();
const nodes = new VectorSource<Feature<Point>>({ wrapX: false }),
edges = new VectorSource<Feature<LineString>>({ wrapX: false }),
faces = new VectorSource<Feature<Polygon>>({ wrapX: false });
topo.on('addnode', (node: Node) => {
const f = new Feature(new Point(node.coordinate));
f.setId(node.id);
nodes.addFeature(f);
});
topo.on('removenode', (node) => {
const f = nodes.getFeatureById(node.id);
if (f) nodes.removeFeature(f);
});
topo.on('addedge', (edge: Edge) => {
const f = new Feature(new LineString(edge.coordinates));
f.setId(edge.id);
edges.addFeature(f);
});
topo.on('modedge', (edge) => edges.getFeatureById(edge.id)?.setGeometry(new LineString(edge.coordinates)));
topo.on('removeedge', (edge) => {
const f = edges.getFeatureById(edge.id);
if (f) edges.removeFeature(f);
});
const updateFace = (face: Face) => {
if (face.id === 0) return;
const coordinates = topo.getFaceGeometry(face),
f = faces.getFeatureById(face.id);
if (f) f.setGeometry(new Polygon(coordinates));
else {
const feature = new Feature(new Polygon(coordinates));
feature.setId(face.id);
faces.addFeature(feature);
}
};
topo.on('addface', updateFace);
topo.on('modface', updateFace);
topo.on('removeface', (face) => {
const f = faces.getFeatureById(face.id);
if (f) faces.removeFeature(f);
});
function node(coordinate: number[]) {
const edge = topo.getEdgeByPoint(coordinate, 5)[0];
return edge ? topo.modEdgeSplit(edge, coordinate) : topo.addIsoNode(coordinate);
}
function draw(input: number[][]): void {
const coordinates = input.map((p) => p.slice());
const first = coordinates[0],
last = coordinates[coordinates.length - 1];
let start = topo.getNodeByPoint(first),
end = topo.getNodeByPoint(last);
const crossing = topo.getEdgesByLine(coordinates);
if (
crossing.length === 1 &&
!start &&
!end &&
!topo.getEdgeByPoint(first, 5).length &&
!topo.getEdgeByPoint(last, 5).length
) {
const edge = crossing[0];
topo.remEdgeNewFace(edge);
if (edge.start.face) topo.removeIsoNode(edge.start);
if (edge.end.face) topo.removeIsoNode(edge.end);
return;
}
start ??= node(first);
end ??= node(last);
coordinates[0] = start.coordinate;
coordinates[coordinates.length - 1] = end.coordinate;
topo.addEdgeNewFaces(start, end, coordinates);
}
if (seed) {
const ring = [
[19.927, 50.058],
[19.945, 50.058],
[19.94, 50.068],
].map((p) => fromLonLat(p));
draw([ring[0], ring[1]]);
draw([ring[1], ring[2]]);
draw([ring[2], ring[0]]);
}
return { nodes, edges, faces, draw };
}topolis.tsimport { 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 Draw from 'ol/interaction/Draw';
import Snap from 'ol/interaction/Snap';
import type LineString from 'ol/geom/LineString';
import { topologyDemo, topologyStyle } from './topolis.shared';
@Component({
selector: 'app-topolis',
imports: [
MapComponent,
ViewComponent,
CoordinateComponent,
LayerTileComponent,
SourceOsmComponent,
DefaultControlComponent,
DefaultInteractionComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './topolis.html',
})
export class Topolis implements AfterViewInit, OnDestroy {
private readonly map = viewChild.required(MapComponent);
private readonly demo = topologyDemo(true);
readonly error = signal(false);
private cleanup = () => {};
ngAfterViewInit(): void {
const map = this.map().instance,
layers = [
new VectorLayer({ source: this.demo.faces, style: topologyStyle('face') }),
new VectorLayer({ source: this.demo.edges, style: topologyStyle('edge') }),
new VectorLayer({ source: this.demo.nodes, style: topologyStyle('node') }),
];
layers.forEach((l) => map.addLayer(l));
const draw = new Draw({ type: 'LineString' }),
snap = new Snap({ source: this.demo.edges });
map.addInteraction(draw);
map.addInteraction(snap);
draw.on('drawend', (e) => {
try {
this.demo.draw((e.feature.getGeometry() as LineString).getCoordinates());
this.error.set(false);
} catch {
this.error.set(true);
}
});
this.cleanup = () => {
map.removeInteraction(draw);
map.removeInteraction(snap);
draw.dispose();
snap.dispose();
layers.forEach((l) => map.removeLayer(l));
};
}
ngOnDestroy(): void {
this.cleanup();
}
} 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.
topolis.react.tsximport { useEffect, useState } from 'react';
import { Map, View, Coordinate, TileLayer, OSMSource, DefaultControls, DefaultInteractions } from 'cc-openlayers/react';
import type OLMap from 'ol/Map';
import VectorLayer from 'ol/layer/Vector';
import Draw from 'ol/interaction/Draw';
import Snap from 'ol/interaction/Snap';
import type LineString from 'ol/geom/LineString';
import { topologyDemo, topologyStyle } from './topolis.shared';
export function Topolis() {
const [map, setMap] = useState<OLMap | null>(null);
const [demo] = useState(() => topologyDemo(true));
const [error, setError] = useState(false);
useEffect(() => {
if (!map) return;
const layers = [
new VectorLayer({ source: demo.faces, style: topologyStyle('face') }),
new VectorLayer({ source: demo.edges, style: topologyStyle('edge') }),
new VectorLayer({ source: demo.nodes, style: topologyStyle('node') }),
];
layers.forEach((l) => map.addLayer(l));
const draw = new Draw({ type: 'LineString' }),
snap = new Snap({ source: demo.edges });
map.addInteraction(draw);
map.addInteraction(snap);
draw.on('drawend', (e) => {
try {
demo.draw((e.feature.getGeometry() as LineString).getCoordinates());
setError(false);
} catch {
setError(true);
}
});
return () => {
map.removeInteraction(draw);
map.removeInteraction(snap);
draw.dispose();
snap.dispose();
layers.forEach((l) => map.removeLayer(l));
};
}, [map, demo]);
return (
<>
<Map ref={setMap} height="480px">
<DefaultControls />
<DefaultInteractions />
<View zoom={13} maxZoom={19}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
</Map>
<div className="example-controls">
<p className="example-hint">Draw connected edges to form faces. Draw across one edge to remove it.</p>
{error ? <p role="alert">The edge could not be added.</p> : null}
</div>
</>
);
}topolis.shared.tsimport './topolis-packages';
import { createTopology } from 'topolis';
import type { Edge, Node, Face } from 'topolis';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import LineString from 'ol/geom/LineString';
import Polygon from 'ol/geom/Polygon';
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 Text from 'ol/style/Text';
import type { FeatureLike } from 'ol/Feature';
import { fromLonLat } from 'ol/proj';
export const topologyStyle = (kind: 'node' | 'edge' | 'face') => (f: FeatureLike) =>
new Style({
image:
kind === 'node'
? new Circle({
radius: 7,
fill: new Fill({ color: 'rgba(230,40,40,.25)' }),
stroke: new Stroke({ color: '#d22', width: 2 }),
})
: undefined,
stroke: new Stroke({ color: kind === 'edge' ? '#27c' : '#151', width: 2 }),
fill: kind === 'face' ? new Fill({ color: 'rgba(30,190,80,.2)' }) : undefined,
text: new Text({
text: String(f.getId()),
fill: new Fill({ color: kind === 'node' ? '#d22' : kind === 'edge' ? '#27c' : '#151' }),
stroke: new Stroke({ color: '#fff', width: 3 }),
}),
});
export function topologyDemo(seed = false) {
const topo = createTopology();
const nodes = new VectorSource<Feature<Point>>({ wrapX: false }),
edges = new VectorSource<Feature<LineString>>({ wrapX: false }),
faces = new VectorSource<Feature<Polygon>>({ wrapX: false });
topo.on('addnode', (node: Node) => {
const f = new Feature(new Point(node.coordinate));
f.setId(node.id);
nodes.addFeature(f);
});
topo.on('removenode', (node) => {
const f = nodes.getFeatureById(node.id);
if (f) nodes.removeFeature(f);
});
topo.on('addedge', (edge: Edge) => {
const f = new Feature(new LineString(edge.coordinates));
f.setId(edge.id);
edges.addFeature(f);
});
topo.on('modedge', (edge) => edges.getFeatureById(edge.id)?.setGeometry(new LineString(edge.coordinates)));
topo.on('removeedge', (edge) => {
const f = edges.getFeatureById(edge.id);
if (f) edges.removeFeature(f);
});
const updateFace = (face: Face) => {
if (face.id === 0) return;
const coordinates = topo.getFaceGeometry(face),
f = faces.getFeatureById(face.id);
if (f) f.setGeometry(new Polygon(coordinates));
else {
const feature = new Feature(new Polygon(coordinates));
feature.setId(face.id);
faces.addFeature(feature);
}
};
topo.on('addface', updateFace);
topo.on('modface', updateFace);
topo.on('removeface', (face) => {
const f = faces.getFeatureById(face.id);
if (f) faces.removeFeature(f);
});
function node(coordinate: number[]) {
const edge = topo.getEdgeByPoint(coordinate, 5)[0];
return edge ? topo.modEdgeSplit(edge, coordinate) : topo.addIsoNode(coordinate);
}
function draw(input: number[][]): void {
const coordinates = input.map((p) => p.slice());
const first = coordinates[0],
last = coordinates[coordinates.length - 1];
let start = topo.getNodeByPoint(first),
end = topo.getNodeByPoint(last);
const crossing = topo.getEdgesByLine(coordinates);
if (
crossing.length === 1 &&
!start &&
!end &&
!topo.getEdgeByPoint(first, 5).length &&
!topo.getEdgeByPoint(last, 5).length
) {
const edge = crossing[0];
topo.remEdgeNewFace(edge);
if (edge.start.face) topo.removeIsoNode(edge.start);
if (edge.end.face) topo.removeIsoNode(edge.end);
return;
}
start ??= node(first);
end ??= node(last);
coordinates[0] = start.coordinate;
coordinates[coordinates.length - 1] = end.coordinate;
topo.addEdgeNewFaces(start, end, coordinates);
}
if (seed) {
const ring = [
[19.927, 50.058],
[19.945, 50.058],
[19.94, 50.068],
].map((p) => fromLonLat(p));
draw([ring[0], ring[1]]);
draw([ring[1], ring[2]]);
draw([ring[2], ring[0]]);
}
return { nodes, edges, faces, draw };
}How the React version works
Draw connected edges and inspect the nodes, edges and faces managed by Topolis.
What both versions share
topolis maintains the planar graph while OpenLayers draws and snaps its visible geometries.
From Angular to React
| Angular | React |
|---|---|
| Lifecycle hooks attach topology layers and signals expose editing errors. | An effect attaches the same topology and useState exposes editing errors. |
| An external Angular template declares the example. | JSX declares the example and its controls. |
| The Angular lifecycle releases the mounted resources. | Effect or subscription cleanup releases the mounted resources. |
Who creates, updates and disposes
Both versions share the graph and its drawing bindings. Cleanup removes the map interactions and display layers.
Architecture and OpenLayers mechanics
Helper topologyDemo initialises a topolis planar topology mirrored live into three OpenLayers vector sources (faces, edges, nodes) mounted as styled VectorLayer instances. An OpenLayers Draw (LineString) + Snap (edges) pair feeds drawn coordinates into demo.draw(...) inside a try / catch block (surfacing invalid-stroke errors via the error signal), and ngOnDestroy disposes of interactions and layers cleanly.
How it works
- The topolis library maintains connected nodes, shared edges and enclosed faces while OpenLayers handles drawing, edge snapping and per-primitive vector styling.
Pitfalls
- In this topological demonstration, sketching a stroke that crosses an existing single edge removes that edge and creates a face according to the demo rules, and self-intersecting or invalid strokes trigger topological exceptions—wrap production parcel workflows with explicit split/merge UX confirmation.
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.