Interactions · Angular, React and OpenLayers
Cut a hole in a polygon
Cut interior exclusion holes inside existing OpenLayers polygons and remove them with Ctrl/Cmd-click using cc-openlayers while exporting GeoJSON.

What this example shows
Over central Kraków, clicking Draw hole lets you click corners inside a blue polygon to carve out an interior courtyard or exclusion enclave around the Old Town, Ctrl-click (or Cmd-click on macOS) an existing hole to remove it, or switch to Select + Modify checkboxes to drag inner and outer vertices while live WGS84 GeoJSON updates below.
When you need it
Cadastral land parcels surrounding inner private plots, agricultural subsidy fields excluding ponds or buildings, and planning zones with protected interior enclaves all require valid multi-ring GeoJSON polygons with interior holes.
Providing a dedicated hole-cutting interaction spares users from complex server-side boolean difference workflows.
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-hole-in-polygon.tsimport { JsonPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import type { Feature as GeoJsonFeature, Polygon as GeoJsonPolygon } from 'geojson';
import type Feature from 'ol/Feature';
import GeoJSON from 'ol/format/GeoJSON';
import Polygon from 'ol/geom/Polygon';
import {
CollectionCoordinatesComponent,
CoordinateComponent,
DefaultInteractionComponent,
FeatureComponent,
GeometryPolygonComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SelectInteractionComponent,
SourceOsmComponent,
SourceVectorComponent,
StyleComponent,
StyleFillComponent,
StyleStrokeComponent,
ViewComponent,
} from 'cc-openlayers';
import {
DrawHoleInPolygonInteractionComponent,
DrawHoleInPolygonInteractionErrorType,
ModifyInteractionComponent,
type DrawHoleInPolygonInteractionError,
} from 'cc-openlayers/editing';
const warnings: Record<DrawHoleInPolygonInteractionErrorType, string> = {
[DrawHoleInPolygonInteractionErrorType.NoPolygonFound]: 'No polygon found to draw hole.',
[DrawHoleInPolygonInteractionErrorType.DrawVertexOutsidePolygon]: 'Cannot add vertex outside the polygon.',
[DrawHoleInPolygonInteractionErrorType.NoLinearRingFoundToRemove]: 'No linear ring found to remove.',
[DrawHoleInPolygonInteractionErrorType.NoVectorLayerFound]: 'No vector layer to draw the hole into.',
};
/** Holes drawn into and removed from a polygon with the library's draw-hole interaction, then selected and edited. */
@Component({
selector: 'app-draw-hole-in-polygon',
imports: [
CollectionCoordinatesComponent,
CoordinateComponent,
DefaultInteractionComponent,
DrawHoleInPolygonInteractionComponent,
FeatureComponent,
GeometryPolygonComponent,
JsonPipe,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
ModifyInteractionComponent,
SelectInteractionComponent,
SourceOsmComponent,
SourceVectorComponent,
StyleComponent,
StyleFillComponent,
StyleStrokeComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px">
<aol-interaction-default />
@if (selecting()) {
<aol-interaction-select #select />
@if (modifying()) {
<aol-interaction-modify
[features]="select.instance.getFeatures()"
(olModifyEnd)="update($event.features.item(0))"
/>
}
}
@if (drawingHole()) {
<aol-interaction-draw-hole-in-polygon (drawEnd)="update($event)" (drawError)="showError($event)" />
}
<aol-view [zoom]="13">
<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>
<aol-style>
<aol-style-stroke color="#167dde" [width]="2" />
<aol-style-fill color="rgba(22, 125, 222, 0.25)" />
</aol-style>
<aol-source-vector>
<aol-feature>
<aol-geometry-polygon>
<aol-collection-coordinates [coordinates]="polygon().geometry.coordinates" srid="EPSG:4326" />
</aol-geometry-polygon>
</aol-feature>
</aol-source-vector>
</aol-layer-vector>
</aol-map>
<div class="example-controls">
<p class="example-hint">
Start a hole by clicking inside the polygon, add vertices and click the first vertex to finish. Ctrl-click (Cmd
on macOS) a hole to remove it.
</p>
<button type="button" [attr.aria-pressed]="drawingHole()" (click)="drawingHole.set(!drawingHole())">
Draw hole
</button>
<label><input type="checkbox" [checked]="selecting()" (change)="selecting.set(checked($event))" /> Select</label>
<label>
<input
type="checkbox"
[checked]="modifying()"
[disabled]="!selecting()"
(change)="modifying.set(checked($event))"
/>
Modify
</label>
</div>
@if (warning(); as message) {
<div role="status" class="warning">
{{ message }}
<button type="button" (click)="warning.set('')">Dismiss</button>
</div>
}
<pre>{{ polygon() | json }}</pre>
`,
})
export class DrawHoleInPolygon {
readonly drawingHole = signal(false);
readonly selecting = signal(false);
readonly modifying = signal(false);
readonly warning = signal('');
readonly polygon = signal<GeoJsonFeature<GeoJsonPolygon>>({
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [
[
[19.9, 50.04],
[19.98, 50.04],
[19.98, 50.08],
[19.9, 50.08],
[19.9, 50.04],
],
],
},
});
private readonly format = new GeoJSON({ dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857' });
protected update(feature: Feature | undefined): void {
if (!(feature?.getGeometry() instanceof Polygon)) return;
this.polygon.set(this.format.writeFeatureObject(feature) as GeoJsonFeature<GeoJsonPolygon>);
}
protected showError(error: DrawHoleInPolygonInteractionError): void {
this.warning.set(warnings[error.type]);
}
protected checked(event: Event): boolean {
return (event.target as HTMLInputElement).checked;
}
} 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-hole-in-polygon.react.tsximport { useState } from 'react';
import type { Feature as GeoJsonFeature, Polygon as GeoJsonPolygon } from 'geojson';
import type OLFeature from 'ol/Feature.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import Polygon from 'ol/geom/Polygon.js';
import type OLSelect from 'ol/interaction/Select.js';
import {
CollectionCoordinates,
Coordinate,
DefaultInteractions,
DrawHoleInPolygonInteraction,
Feature,
Fill,
Map,
ModifyInteraction,
OSMSource,
PolygonGeometry,
SelectInteraction,
Stroke,
Style,
TileLayer,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
import { DrawHoleInPolygonInteractionErrorType, type PolygonHoleDrawingError } from 'cc-openlayers/core';
const warnings: Record<DrawHoleInPolygonInteractionErrorType, string> = {
[DrawHoleInPolygonInteractionErrorType.NoPolygonFound]: 'No polygon found to draw hole.',
[DrawHoleInPolygonInteractionErrorType.DrawVertexOutsidePolygon]: 'Cannot add vertex outside the polygon.',
[DrawHoleInPolygonInteractionErrorType.NoLinearRingFoundToRemove]: 'No linear ring found to remove.',
[DrawHoleInPolygonInteractionErrorType.NoVectorLayerFound]: 'No vector layer to draw the hole into.',
};
const format = new GeoJSON({ dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857' });
const initialPolygon: GeoJsonFeature<GeoJsonPolygon> = {
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [
[
[19.9, 50.04],
[19.98, 50.04],
[19.98, 50.08],
[19.9, 50.08],
[19.9, 50.04],
],
],
},
};
/** Holes drawn into and removed from a polygon with the library's draw-hole interaction, then selected and edited. */
export function DrawHoleInPolygon() {
const [drawingHole, setDrawingHole] = useState(false);
const [selecting, setSelecting] = useState(false);
const [modifying, setModifying] = useState(false);
const [warning, setWarning] = useState('');
const [polygon, setPolygon] = useState(initialPolygon);
const [select, setSelect] = useState<OLSelect | null>(null);
const update = (feature: OLFeature | undefined) => {
if (!(feature?.getGeometry() instanceof Polygon)) return;
setPolygon(format.writeFeatureObject(feature) as GeoJsonFeature<GeoJsonPolygon>);
};
const showError = (error: PolygonHoleDrawingError) => setWarning(warnings[error.code]);
return (
<>
<Map height="480px">
<DefaultInteractions />
{selecting ? <SelectInteraction ref={setSelect} /> : null}
{selecting && select && modifying ? (
<ModifyInteraction features={select.getFeatures()} onModifyEnd={(event) => update(event.features.item(0))} />
) : null}
{drawingHole ? <DrawHoleInPolygonInteraction onDrawEnd={update} onDrawError={showError} /> : null}
<View zoom={13}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
<VectorLayer>
<Style>
<Stroke color="#167dde" width={2} />
<Fill color="rgba(22, 125, 222, 0.25)" />
</Style>
<VectorSource>
<Feature>
<PolygonGeometry>
<CollectionCoordinates coordinates={polygon.geometry.coordinates} srid="EPSG:4326" />
</PolygonGeometry>
</Feature>
</VectorSource>
</VectorLayer>
</Map>
<div className="example-controls">
<p className="example-hint">
Start a hole by clicking inside the polygon, add vertices and click the first vertex to finish. Ctrl-click
(Cmd on macOS) a hole to remove it.
</p>
<button type="button" aria-pressed={drawingHole} onClick={() => setDrawingHole(!drawingHole)}>
Draw hole
</button>
<label>
<input type="checkbox" checked={selecting} onChange={(event) => setSelecting(event.target.checked)} /> Select
</label>
<label>
<input
type="checkbox"
checked={modifying}
disabled={!selecting}
onChange={(event) => setModifying(event.target.checked)}
/>
Modify
</label>
</div>
{warning ? (
<div role="status" className="warning">
{warning}
<button type="button" onClick={() => setWarning('')}>
Dismiss
</button>
</div>
) : null}
<pre>{JSON.stringify(polygon, null, 2)}</pre>
</>
);
}How the React version works
Holes drawn into and removed from a polygon with the library's draw-hole interaction; Select and Modify then edit the result, and drawing errors are explained until dismissed.
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 draw-hole interaction comes from cc-openlayers/core; in React its errors carry a code, as library errors do.
From Angular to React
| Angular | React |
|---|---|
the Draw hole button's (click) and @if | onClick toggling useState and a conditional <DrawHoleInPolygonInteraction> |
(drawEnd) and (drawError) | onDrawEnd and onDrawError; the error message lives in useState |
<aol-interaction-modify> on the select's features | <ModifyInteraction> on select.getFeatures(), with the select from ref={setSelect} |
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
aol-interaction-draw-hole-in-polygon (provided natively by cc-openlayers) validates that clicks land inside an existing target polygon, appends the finished linear ring as an interior hole of that polygon, and supports one-click hole deletion via Ctrl/Cmd-click.
Independent @if toggles mount hole drawing and Select + Modify vertex editing, so both modes can be active at once; every update serialises to geographic GeoJSON in a signal while dismissible validation banners appear whenever a user clicks outside the host polygon.
How it works
aol-interaction-draw-hole-in-polygoncuts interior rings inside clicked polygons and deletes holes on Ctrl-click (Cmd-click on macOS).- Independent
@ifcontrols keep Draw hole andSelect+Modifyboth mountable, matching the template. - Every added, edited or removed hole serialises immediately to geographic GeoJSON stored in reactive state.
- Out-of-bounds clicks surface clear validation messages with a Dismiss button.
Pitfalls
- OGC Simple Features and GeoJSON require every interior hole ring to lie strictly within its exterior shell without self-intersections—validate ring containment so downstream spatial databases never reject saved edits.
- Keep Draw-hole and Select/Modify modes mutually exclusive so clicks inside a polygon do not trigger selection changes mid-sketch.
Related examples
Background: state and lifecycle of maps in Angular with OpenLayers, which the components of cc-openlayers take care of.