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.

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.tsimport { 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;
};
} 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.
custom-interactions.react.tsximport { useEffect, useState } from 'react';
import type { Coordinate as OLCoordinate } from 'ol/coordinate.js';
import Feature, { type FeatureLike } from 'ol/Feature.js';
import type Geometry from 'ol/geom/Geometry.js';
import LineString from 'ol/geom/LineString.js';
import Point from 'ol/geom/Point.js';
import Polygon from 'ol/geom/Polygon.js';
import type MapBrowserEvent from 'ol/MapBrowserEvent.js';
import type OLVectorSource from 'ol/source/Vector.js';
import { fromLonLat } from 'ol/proj.js';
import type { FlatStyle } from 'ol/style/flat.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
Map,
OGCMapTileSource,
PointerInteraction,
TileLayer,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
/** 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],
];
/** The map tiles of the default style in the service's Web Mercator tile matrix set. */
const url = `${EURO_REGIONAL_MAP}/collections/erm/styles/default/map/tiles/euro_3857`;
const 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],
};
const CURSOR = 'pointer';
/** The handlers of one custom interaction, which share the feature being dragged. OpenLayers reads them once. */
function createHandlers() {
let coordinate: OLCoordinate | null = null;
let feature: FeatureLike | null = null;
let previousCursor: string | undefined = undefined;
return {
/** Starts the drag sequence on a feature. */
handleDownEvent: (evt: MapBrowserEvent): boolean => {
const map = evt.map;
const hit = map.forEachFeatureAtPixel(evt.pixel, function (found) {
return found;
});
if (hit) {
coordinate = evt.coordinate;
feature = hit;
}
return !!hit;
},
handleDragEvent: (evt: MapBrowserEvent): void => {
const start = coordinate as OLCoordinate;
const deltaX = evt.coordinate[0] - start[0];
const deltaY = evt.coordinate[1] - start[1];
const geometry = (feature as Feature).getGeometry() as Geometry;
geometry.translate(deltaX, deltaY);
start[0] = evt.coordinate[0];
start[1] = evt.coordinate[1];
},
handleMoveEvent: (evt: MapBrowserEvent): void => {
if (CURSOR) {
const map = evt.map;
const hit = map.forEachFeatureAtPixel(evt.pixel, function (found) {
return found;
});
const element = evt.map.getTargetElement() as HTMLElement;
if (hit) {
if (element.style.cursor != CURSOR) {
previousCursor = element.style.cursor;
element.style.cursor = CURSOR;
}
} else if (previousCursor !== undefined) {
element.style.cursor = previousCursor;
previousCursor = undefined;
}
}
},
/** Ends the drag sequence. */
handleUpEvent: (): boolean => {
coordinate = null;
feature = null;
return false;
},
};
}
function createFeatures() {
return [
new Feature(new Point(fromLonLat([19.9373, 50.0617]))),
new Feature(new LineString([fromLonLat([19.8932, 50.0549]), fromLonLat([19.9584, 50.0381])])),
new Feature(new Polygon([BLONIA.map((coordinate) => fromLonLat(coordinate))])),
];
}
/**
* A custom interaction that drags any feature with the pointer, made of the handlers of a `PointerInteraction`:
* 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.
*/
export function CustomInteractions() {
const [handlers] = useState(createHandlers);
const [features] = useState(createFeatures);
// The source is made after the first commit, so the state carries it to the effect.
const [source, setSource] = useState<OLVectorSource | null>(null);
useEffect(() => {
source?.addFeatures(features);
return () => {
for (const feature of features) source?.removeFeature(feature);
};
}, [source, features]);
return (
<Map height="480px">
<DefaultInteractions />
<PointerInteraction
handleDownEvent={handlers.handleDownEvent}
handleDragEvent={handlers.handleDragEvent}
handleMoveEvent={handlers.handleMoveEvent}
handleUpEvent={handlers.handleUpEvent}
/>
<DefaultControls />
<View zoom={13}>
<Coordinate x={19.925} y={50.052} srid="EPSG:4326" />
</View>
<TileLayer>
{/* The service names its CRS with a URI OpenLayers cannot resolve: the projection is given instead. */}
<OGCMapTileSource url={url} projection="EPSG:3857" attributions="© EuroGeographics (EuroRegionalMap)" />
</TileLayer>
<VectorLayer style={style}>
<VectorSource ref={setSource} />
</VectorLayer>
</Map>
);
}How the React version works
A custom interaction made of a PointerInteraction's handlers drags any feature: a point on the 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.
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. Both versions use the same handler functions, which keep the drag state between events.
From Angular to React
| Angular | React |
|---|---|
<aol-interaction-pointer [handleDownEvent] [handleDragEvent] [handleMoveEvent] [handleUpEvent]> | <PointerInteraction handleDownEvent handleDragEvent handleMoveEvent handleUpEvent> with handlers made once |
afterNextRender adding the features to viewChild of the source | ref={setSource} into useState and a useEffect that adds the features and removes them in its cleanup |
<aol-source-ogcmaptile> | <OGCMapTileSource> |
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
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-pointerwireshandleDownEvent,handleDragEvent,handleMoveEventandhandleUpEventwithout subclassing.- Returning true from
handleDownEventwhenforEachFeatureAtPixelhits a feature starts a drag sequence and suppresses map panning. handleDragEventcallstranslateon the grabbed geometry with the coordinate delta since the previous pointer tick.handleMoveEventmanages hover cursor feedback, and returningfalsefromhandleUpEventterminates 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-pointerafteraol-interaction-defaultin the template so DragPan does not swallow pointer drags first.
Related examples
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.