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.

A blue polygon over central Kraków with a hole cut into it around the Old Town, the Draw hole button and the Select and Modify checkboxes below, and its GeoJSON.
A screenshot of the example. Map data © OpenStreetMap contributors.

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.ts
import { 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;
  }
}

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-polygon cuts interior rings inside clicked polygons and deletes holes on Ctrl-click (Cmd-click on macOS).
  • Independent @if controls keep Draw hole and Select + Modify both 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.

Background: state and lifecycle of maps in Angular with OpenLayers, which the components of cc-openlayers take care of.