Interactions · Angular, React and OpenLayers

A custom drag interaction

Build a custom OpenLayers feature-dragging interaction declaratively in Angular and React using four arrow-function Pointer event handlers.

A EuroRegionalMap view of Kraków with a blue polygon on the Błonia, a red line across the city and a pin dragged by its head from the Main Square onto Wawel.
A screenshot of the example. EuroRegionalMap © EuroGeographics, served by CubeWerx's OGC API demonstration server.

What this example shows

Over EuroGeographics’ EuroRegionalMap of Kraków, a blue polygon on Błonia, a red polyline across the city and a map pin on Wawel can all be grabbed and dragged smoothly across the canvas, with automatic pointer-cursor hover feedback—powered by a custom four-handler Pointer interaction.

When you need it

Bespoke interactive tools—magnetic alignment guides, custom measurement callouts, azimuth protractors or specialized drag tools—sometimes need raw down/drag/move/up pointer state machines beyond built-in Draw, Modify or Translate classes.

Passing four handler functions directly to aol-interaction-pointer gives you full custom interaction control inside your component without boilerplate ES6 subclassing of ol/interaction/Pointer.

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.

custom-interactions.ts
import { afterNextRender, ChangeDetectionStrategy, Component, viewChild } from '@angular/core';
import type { Coordinate } from 'ol/coordinate';
import Feature, { type FeatureLike } from 'ol/Feature';
import type Geometry from 'ol/geom/Geometry';
import LineString from 'ol/geom/LineString';
import Point from 'ol/geom/Point';
import Polygon from 'ol/geom/Polygon';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import { fromLonLat } from 'ol/proj';
import type { FlatStyle } from 'ol/style/flat';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  PointerInteractionComponent,
  SourceOGCMapTileComponent,
  SourceVectorComponent,
  ViewComponent,
} from 'cc-openlayers';

/** EuroGeographics' EuroRegionalMap on CubeWerx's OGC API demonstration server. */
const EURO_REGIONAL_MAP = 'https://test.cubewerx.com/cubewerx/cubeserv/demo/ogcapi/EuroRegionalMap';

/** The outline of the Błonia meadow west of the Old Town (OpenStreetMap, simplified). */
const BLONIA = [
  [19.9068, 50.0594],
  [19.9052, 50.0583],
  [19.901, 50.0605],
  [19.9025, 50.0624],
  [19.9231, 50.0592],
  [19.9073, 50.057],
  [19.909, 50.058],
  [19.9068, 50.0594],
];

/**
 * A custom interaction that drags any feature with the pointer, made of the handlers of an `aol-interaction-pointer`:
 * a point on Kraków's Main Square, a line between the Kościuszko and Krakus mounds and a polygon on the Błonia meadow.
 * The cursor turns into a pointer over a feature.
 */
@Component({
  selector: 'app-custom-interactions',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    PointerInteractionComponent,
    SourceOGCMapTileComponent,
    SourceVectorComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-interaction-pointer
        [handleDownEvent]="handleDownEvent"
        [handleDragEvent]="handleDragEvent"
        [handleMoveEvent]="handleMoveEvent"
        [handleUpEvent]="handleUpEvent"
      />
      <aol-control-defaults />
      <aol-view [zoom]="13">
        <aol-coordinate [x]="19.925" [y]="50.052" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile>
        <!-- The service names its CRS with a URI OpenLayers cannot resolve: the projection is given instead. -->
        <aol-source-ogcmaptile [url]="url" projection="EPSG:3857" attributions="© EuroGeographics (EuroRegionalMap)" />
      </aol-layer-tile>
      <aol-layer-vector [style]="style">
        <aol-source-vector />
      </aol-layer-vector>
    </aol-map>
  `,
})
export class CustomInteractions {
  /** The map tiles of the default style in the service's Web Mercator tile matrix set. */
  protected readonly url = `${EURO_REGIONAL_MAP}/collections/erm/styles/default/map/tiles/euro_3857`;
  protected readonly style: FlatStyle = {
    'icon-src': 'assets/marker.svg',
    'icon-opacity': 0.95,
    // marker.svg's pin has its tip 22 pixels below the top.
    'icon-anchor': [0.5, 22],
    'icon-anchor-x-units': 'fraction',
    'icon-anchor-y-units': 'pixels',
    'stroke-width': 3,
    'stroke-color': [255, 0, 0, 1],
    'fill-color': [0, 0, 255, 0.6],
  };
  readonly pointFeature = new Feature(new Point(fromLonLat([19.9373, 50.0617])));
  readonly lineFeature = new Feature(new LineString([fromLonLat([19.8932, 50.0549]), fromLonLat([19.9584, 50.0381])]));
  readonly polygonFeature = new Feature(new Polygon([BLONIA.map((coordinate) => fromLonLat(coordinate))]));

  private coordinate: Coordinate | null = null;
  private readonly cursor = 'pointer';
  private feature: FeatureLike | null = null;
  private previousCursor: string | undefined = undefined;
  private readonly source = viewChild.required(SourceVectorComponent);

  constructor() {
    afterNextRender(() =>
      this.source().instance.addFeatures([this.pointFeature, this.lineFeature, this.polygonFeature])
    );
  }

  /** Starts the drag sequence on a feature. */
  protected readonly handleDownEvent = (evt: MapBrowserEvent): boolean => {
    const map = evt.map;

    const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
      return feature;
    });

    if (feature) {
      this.coordinate = evt.coordinate;
      this.feature = feature;
    }

    return !!feature;
  };

  protected readonly handleDragEvent = (evt: MapBrowserEvent): void => {
    const coordinate = this.coordinate as Coordinate;
    const deltaX = evt.coordinate[0] - coordinate[0];
    const deltaY = evt.coordinate[1] - coordinate[1];

    const geometry = (this.feature as Feature).getGeometry() as Geometry;
    geometry.translate(deltaX, deltaY);

    coordinate[0] = evt.coordinate[0];
    coordinate[1] = evt.coordinate[1];
  };

  protected readonly handleMoveEvent = (evt: MapBrowserEvent): void => {
    if (this.cursor) {
      const map = evt.map;
      const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
        return feature;
      });
      const element = evt.map.getTargetElement() as HTMLElement;
      if (feature) {
        if (element.style.cursor != this.cursor) {
          this.previousCursor = element.style.cursor;
          element.style.cursor = this.cursor;
        }
      } else if (this.previousCursor !== undefined) {
        element.style.cursor = this.previousCursor;
        this.previousCursor = undefined;
      }
    }
  };

  /** Ends the drag sequence. */
  protected readonly handleUpEvent = (): boolean => {
    this.coordinate = null;
    this.feature = null;
    return false;
  };
}

Architecture and OpenLayers mechanics

Mounted after aol-interaction-default so it receives pointer events ahead of DragPan, aol-interaction-pointer binds four arrow-function callbacks: handleDownEvent checks forEachFeatureAtPixel and returns true on a hit to claim the drag sequence; handleDragEvent shifts the hit geometry by the delta coordinate via translate; handleMoveEvent toggles the viewport cursor over features; and handleUpEvent clears state and returns false to end the drag.

How it works

  • aol-interaction-pointer wires handleDownEvent, handleDragEvent, handleMoveEvent and handleUpEvent without subclassing.
  • Returning true from handleDownEvent when forEachFeatureAtPixel hits a feature starts a drag sequence and suppresses map panning.
  • handleDragEvent calls translate on the grabbed geometry with the coordinate delta since the previous pointer tick.
  • handleMoveEvent manages hover cursor feedback, and returning false from handleUpEvent terminates the drag sequence.

Pitfalls

  • OpenLayers invokes Pointer callbacks with the underlying OpenLayers interaction bound as this—always define component handlers as lexical arrow functions (const handleDown = (event) => ...) when referencing component state.
  • Declare aol-interaction-pointer after aol-interaction-default in the template so DragPan does not swallow pointer drags first.

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.