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.

An orthophoto around Kraków with the municipalities in red and a green polygon traced along the city's northern border and closed inside it, with Modify only below.
A screenshot of the example. Municipal boundaries: Państwowy Rejestr Granic © GUGiK. Orthophotomap © GUGiK.

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

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] on aol-interaction-draw copy municipal border vertices between two clicks while sketching.
  • Matching [trace] and [traceSource] inputs on aol-interaction-modify trace 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 traceSource on 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.

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.