Interactions · Angular, React and OpenLayers
Drag an icon to another place
Drag a tall SVG map pin smoothly by any painted pixel of its icon in OpenLayers using Modify hitDetection and grab/pointer cursor feedback.

What this example shows
Over EuroGeographics’ EuroRegionalMap of Kraków, a map pin starting at the Barbican can be picked up anywhere across its wide upper head—not merely at its tiny bottom tip—and dragged smoothly onto the Main Square, showing a pointer hand on hover and a closed grabbing hand while dragging.
When you need it
Users correcting an address pin, repositioning a delivery stop or placing photo markers instinctively grab the visible head of a map pin rather than aiming 22 pixels lower at its coordinate tip.
Enabling layer-based pixel hit detection on the Modify interaction makes tall or offset icons effortless to pick up with both mouse and touch.
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.
modify-icon.tsimport { afterNextRender, ChangeDetectionStrategy, Component, viewChild } from '@angular/core';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import type VectorSource from 'ol/source/Vector';
import { fromLonLat } from 'ol/proj';
import Icon from 'ol/style/Icon';
import Style from 'ol/style/Style';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceOGCMapTileComponent,
SourceVectorComponent,
ViewComponent,
} from 'cc-openlayers';
import { ModifyInteractionComponent } from 'cc-openlayers/editing';
const EURO_REGIONAL_MAP = 'https://test.cubewerx.com/cubewerx/cubeserv/demo/ogcapi/EuroRegionalMap';
/** The Barbican, the fortified gate north of the Old Town. */
const BARBICAN = [19.9417, 50.0655];
const iconStyle = new Style({
image: new Icon({
// marker.svg's pin has its tip 22 pixels below the top.
anchor: [0.5, 22],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'assets/marker.svg',
}),
});
/**
* An icon on Kraków's Barbican that can be dragged to another place: the Modify interaction finds it by where the
* icon layer draws it (`hitDetection`) rather than by a pixel tolerance around its point, and the cursor shows when
* it can be grabbed.
*/
@Component({
selector: 'app-modify-icon',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
ModifyInteractionComponent,
SourceOGCMapTileComponent,
SourceVectorComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="12">
<aol-coordinate [x]="barbican[0]" [y]="barbican[1]" 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 #vectorLayer><aol-source-vector #vectorSource /></aol-layer-vector>
<aol-interaction-modify
[hitDetection]="vectorLayer.instance"
[source]="vectorSource.instance"
(olModifyStart)="cursor('grabbing')"
(olModifyEnd)="cursor('pointer')"
/>
</aol-map>
`,
})
export class ModifyIcon {
protected readonly barbican = BARBICAN;
/** 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`;
readonly iconFeature = new Feature({
geometry: new Point(fromLonLat(BARBICAN)),
name: 'Barbican',
});
private readonly map = viewChild.required(MapComponent);
private readonly source = viewChild.required(SourceVectorComponent);
private readonly modify = viewChild.required(ModifyInteractionComponent);
constructor() {
this.iconFeature.setStyle(iconStyle);
afterNextRender(() => {
this.source().instance.addFeature(this.iconFeature);
const overlaySource = this.modify().instance.getOverlay().getSource() as VectorSource;
overlaySource.on(['addfeature', 'removefeature'], (evt) => {
this.cursor(evt.type === 'addfeature' ? 'pointer' : '');
});
});
}
protected cursor(cursor: string): void {
(this.map().instance.getTargetElement() as HTMLElement).style.cursor = cursor;
}
} 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.
modify-icon.react.tsximport { useEffect, useRef, useState } from 'react';
import Feature from 'ol/Feature.js';
import type OLMap from 'ol/Map.js';
import Point from 'ol/geom/Point.js';
import type OLModify from 'ol/interaction/Modify.js';
import type OLVectorLayer from 'ol/layer/Vector.js';
import { fromLonLat } from 'ol/proj.js';
import type OLVectorSource from 'ol/source/Vector.js';
import Icon from 'ol/style/Icon.js';
import Style from 'ol/style/Style.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
Map,
ModifyInteraction,
OGCMapTileSource,
TileLayer,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
const EURO_REGIONAL_MAP = 'https://test.cubewerx.com/cubewerx/cubeserv/demo/ogcapi/EuroRegionalMap';
/** The Barbican, the fortified gate north of the Old Town. */
const BARBICAN = [19.9417, 50.0655];
/** 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 iconStyle = new Style({
image: new Icon({
// marker.svg's pin has its tip 22 pixels below the top.
anchor: [0.5, 22],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'assets/marker.svg',
}),
});
function createIconFeature(): Feature {
const iconFeature = new Feature({
geometry: new Point(fromLonLat(BARBICAN)),
name: 'Barbican',
});
iconFeature.setStyle(iconStyle);
return iconFeature;
}
/**
* An icon on Kraków's Barbican that can be dragged to another place: the Modify interaction finds it by where the
* icon layer draws it (`hitDetection`) rather than by a pixel tolerance around its point, and the cursor shows when
* it can be grabbed.
*/
export function ModifyIcon() {
const [iconFeature] = useState(createIconFeature);
const map = useRef<OLMap>(null);
// The layer, the source and the interaction are made after the first commit, so state carries them to the effects.
const [layer, setLayer] = useState<OLVectorLayer | null>(null);
const [source, setSource] = useState<OLVectorSource | null>(null);
const [modify, setModify] = useState<OLModify | null>(null);
const cursor = (value: string) => {
(map.current?.getTargetElement() as HTMLElement).style.cursor = value;
};
useEffect(() => {
source?.addFeature(iconFeature);
return () => source?.removeFeature(iconFeature);
}, [source, iconFeature]);
useEffect(() => {
const overlaySource = modify?.getOverlay().getSource() as OLVectorSource | undefined;
if (!overlaySource) return;
const listener = (event: { type: string }) => {
(map.current?.getTargetElement() as HTMLElement).style.cursor = event.type === 'addfeature' ? 'pointer' : '';
};
overlaySource.on(['addfeature', 'removefeature'], listener);
return () => overlaySource.un(['addfeature', 'removefeature'], listener);
}, [modify]);
return (
<Map ref={map} height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={12}>
<Coordinate x={BARBICAN[0]} y={BARBICAN[1]} 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 ref={setLayer}>
<VectorSource ref={setSource} />
</VectorLayer>
{layer && source ? (
<ModifyInteraction
ref={setModify}
hitDetection={layer}
source={source}
onModifyStart={() => cursor('grabbing')}
onModifyEnd={() => cursor('pointer')}
/>
) : null}
</Map>
);
}How the React version works
An icon on the Barbican that can be dragged elsewhere: the modify interaction finds it where the icon layer draws it (hitDetection) rather than by a pixel tolerance; the cursor shows when the icon can be grabbed and while it is dragged.
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.
From Angular to React
| Angular | React |
|---|---|
<aol-source-ogcmaptile> | <OGCMapTileSource> |
afterNextRender and viewChild of the source, the layer and the modify interaction | ref={setSource}, ref={setLayer} and ref={setModify} into useState, with effects keyed on them |
| a listener on the modify overlay's source for the cursor | the same listener added in a useEffect and removed in its cleanup |
(olModifyStart) and (olModifyEnd) for the grabbing cursor | onModifyStart and onModifyEnd |
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. The effects add the feature to the source and the cursor listener to the overlay, and their cleanups remove both.
Architecture and OpenLayers mechanics
The point feature styles itself via setStyle with a 24-pixel marker.svg whose anchor places the bottom tip on the coordinate. Passing the vector layer to [hitDetection] on Modify tells OpenLayers to test rendered icon pixels across the layer canvas rather than checking Euclidean distance to the point coordinate.
Observing addfeature and removal on Modify’s internal vertex overlay toggles the hover pointer cursor, while olModifyStart and olModifyEnd switch to a grabbing-hand cursor during active drags.
How it works
- Binding the marker layer to
[hitDetection]lets Modify grab the pin anywhere across its rendered SVG silhouette. - Icon
anchorkeeps the bottom tip (22 px down from the top ofmarker.svg) registered on the geographic coordinate. - Modify’s overlay
addfeatureevent andolModifyStart/olModifyEnddrive responsive pointer and grabbing-hand CSS cursors. - The component assigns the style with
setStyleand adds the feature withaddFeatureinafterNextRender.
Pitfalls
- Without
[hitDetection], Modify only activates within pixelTolerance (10 px by default) of the raw Point coordinate—leaving the upper bulb of the 24-pixel pin completely ungrabbable. - Cross-origin icon images served without CORS headers cannot have their alpha channel inspected, causing hit detection to treat the entire rectangular bounding box around the icon as opaque.
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.