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.

A EuroRegionalMap view of Kraków with the pin dragged from the Barbican onto the Main Square and the blue vertex of the modify interaction at its tip.
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 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.ts
import { 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;
  }
}

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 anchor keeps the bottom tip (22 px down from the top of marker.svg) registered on the geographic coordinate.
  • Modify’s overlay addfeature event and olModifyStart / olModifyEnd drive responsive pointer and grabbing-hand CSS cursors.
  • The component assigns the style with setStyle and adds the feature with addFeature in afterNextRender.

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.

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.