Interactions · Angular, React and OpenLayers

Snap to the middle of segments

Snap drawn and edited lines in OpenLayers to exact segment midpoints as well as vertices and edges using a custom Snap segmenters function.

A zigzag of three thin yellow segments on a dark background and a line drawn straight through their midpoints, which the custom segmenter makes snap targets.
A screenshot of the example. No map data: the lines are drawn on the example's empty layer.

What this example shows

On a dark background canvas, drawing or modifying lines snaps your cursor not only to existing endpoints and anywhere along segment edges, but also locks crisply onto the exact geometric midpoint of every segment.

When you need it

CAD-style site drafting, T-junction utility service taps, perpendicular bisectors and architectural parcel splits regularly connect straight into the exact midpoint of an existing wall, pipe or lot line.

OpenLayers’ custom segmenters option injects synthetic snap points—midpoints, quarter-points or offset anchors—directly into Snap’s spatial index without cluttering your vector source with dummy helper features.

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.

snap-custom-segmenter.ts
import { ChangeDetectionStrategy, Component } from '@angular/core';
import type { Coordinate } from 'ol/coordinate';
import type LineString from 'ol/geom/LineString';
import type { Segment } from 'ol/interaction/Snap';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerVectorComponent,
  MapComponent,
  SourceVectorComponent,
  ViewComponent,
} from 'cc-openlayers';
import { DrawInteractionComponent, ModifyInteractionComponent, SnapInteractionComponent } from 'cc-openlayers/editing';

/** Lines drawn and modified on a dark map, with a custom segmenter making the midpoint of each segment snap too. */
@Component({
  selector: 'app-snap-custom-segmenter',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    DrawInteractionComponent,
    LayerVectorComponent,
    MapComponent,
    ModifyInteractionComponent,
    SnapInteractionComponent,
    SourceVectorComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="13"><aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" /></aol-view>
      <aol-layer-vector background="#333" [style]="style">
        <aol-source-vector #source />
      </aol-layer-vector>
      <aol-interaction-modify [source]="source.instance" />
      <aol-interaction-draw type="LineString" [source]="source.instance" />
      <aol-interaction-snap [source]="source.instance" [segmenters]="segmenters" />
    </aol-map>
    <div class="example-controls">
      <p class="example-hint">Draw a line: its vertices and the midpoint of each segment attract the pointer.</p>
    </div>
  `,
})
export class SnapCustomSegmenter {
  protected readonly style = { 'stroke-color': '#ffcc33' };
  /** Each segment of a line snaps as itself and as its midpoint, a segment of one point. */
  protected readonly segmenters = {
    LineString: (geometry: LineString): Segment[] => {
      const segments: Segment[] = [];
      geometry.forEachSegment((start: Coordinate, end: Coordinate) => {
        segments.push([start, end], [[(start[0] + end[0]) / 2, (start[1] + end[1]) / 2]]);
      });
      return segments;
    },
  };
}

Architecture and OpenLayers mechanics

Passing a LineString handler inside segmenters overrides how aol-interaction-snap decomposes lines into snap primitives while leaving polygons and points at their defaults. Walking the line with forEachSegment, the function emits both the full two-point [start, end] edge segment and a degenerate single-coordinate [[midX, midY]] entry—which OpenLayers’ Snap interaction treats as a high-priority vertex point target.

Mounting Snap last in the template after Modify and Draw applies midpoint snapping to both new sketches and vertex drags.

How it works

  • Custom segmenters override segment decomposition for LineString geometries while keeping default snapping for other types.
  • Using forEachSegment, each segment yields both [start, end] (edge snapping) and a single-point midpoint entry (point snapping).
  • Placing Snap after Modify and Draw on the shared source enables midpoint snapping during both drawing and editing.
  • Yellow flat-styled lines stand out clearly against the dark layer background.

Pitfalls

  • A custom segmenter replaces OpenLayers’ default segmenter for that geometry type completely—always include [start, end] alongside your custom midpoint in the returned array, otherwise normal edge snapping along the segment disappears.
  • An in-progress sketch is not added to the vector source until finished, so its own uncommitted segments become midpoint snap targets only after completion.

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.