Interactions · Angular, React and OpenLayers

Find features with a layer's hit detection

Accelerate high-frequency hover hit-testing over dense polygons in OpenLayers using asynchronous layer.getFeatures() and highlight overlays.

Poland's voivodeships in flat colours on a dark background with Małopolska outlined under the pointer, and its name and code 12 below the map.
A screenshot of the example. Voivodeships: Państwowy Rejestr Granic © GUGiK.

What this example shows

Across Poland’s 16 voivodeships styled with a code-driven match expression on a dark background, sweeping the pointer rapidly across the map outlines the hovered province in white and displays its name and two-digit TERYT code below—using the vector layer’s fast internal hit-detection buffer.

When you need it

Evaluating map.forEachFeatureAtPixel on every pointermove across thousands of complex multi-vertex polygons can contend with 60 fps rendering on lower-powered devices.

VectorLayer’s own layer.getFeatures(pixel) queries a dedicated half-resolution off-screen colour-coded hit image—trading sub-pixel border precision for fast, constant-time pixel lookups.

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.

hitdetect-vector.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerVectorComponent,
  MapComponent,
  SourceGeoJSONComponent,
  SourceVectorComponent,
  ViewComponent,
} from 'cc-openlayers';
import Feature from 'ol/Feature';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import type { FlatStyle } from 'ol/style/flat';

const PALETTE = [
  '#4e79a7',
  '#f28e2b',
  '#e15759',
  '#76b7b2',
  '#59a14f',
  '#edc948',
  '#b07aa1',
  '#ff9da7',
  '#9c755f',
  '#bab0ac',
  '#86bcb6',
  '#d37295',
  '#fabfd2',
  '#b6992d',
  '#499894',
  '#79706e',
];

/** The colour of each voivodeship by its code: 02 is the first colour of the palette, 04 the second and so on. */
const FILL: FlatStyle['fill-color'] = [
  'match',
  ['get', 'code'],
  ...PALETTE.flatMap((color, index) => [String((index + 1) * 2).padStart(2, '0'), color]),
  '#eee',
];

/** Voivodeships found under the pointer with the layer's hit detection, highlighted and named on hover and click. */
@Component({
  selector: 'app-hitdetect-vector',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerVectorComponent,
    MapComponent,
    SourceGeoJSONComponent,
    SourceVectorComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px" (pointerMove)="show($event)" (olClick)="show($event)">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="6"><aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" /></aol-view>
      <aol-layer-vector background="#1a2b39" [style]="fillStyle">
        <aol-source-geojson url="assets/poland/voivodeships.geojson" />
      </aol-layer-vector>
      <aol-layer-vector [style]="highlightStyle"><aol-source-vector /></aol-layer-vector>
    </aol-map>
    <div class="example-controls">
      <p class="example-hint">Move the pointer over a voivodeship or click it.</p>
      <span>
        Voivodeship <output>{{ info() }}</output>
      </span>
    </div>
  `,
})
export class HitdetectVector {
  readonly info = signal('–');
  protected readonly fillStyle: FlatStyle = { 'fill-color': FILL };
  protected readonly highlightStyle: FlatStyle = { 'stroke-color': 'rgba(255, 255, 255, 0.7)', 'stroke-width': 2 };
  private readonly layers = viewChild.required(LayerVectorComponent);
  private readonly overlay = viewChild.required(SourceVectorComponent);
  private highlight?: Feature;

  protected show(event: MapBrowserEvent): void {
    if (event.dragging) return;
    void this.layers()
      .instance.getFeatures(event.pixel)
      .then((features) => {
        const feature = features.find((candidate) => candidate instanceof Feature);
        this.info.set(feature ? `${feature.get('name')}: ${feature.get('code')}` : '–');
        if (feature === this.highlight) return;
        const source = this.overlay().instance;
        if (this.highlight) source.removeFeature(this.highlight);
        if (feature) source.addFeature(feature);
        this.highlight = feature;
      });
  }
}

Architecture and OpenLayers mechanics

On pointerMove (skipping active drags via event.dragging) and olClick, calling getFeatures directly on the vector layer resolves a Promise containing the topmost hit feature from its half-resolution hit buffer.

Helper highlight compares the resolved feature against the currently highlighted one before mutating the dedicated white-outline overlay source—avoiding redundant redraws when the pointer moves within the same voivodeship.

How it works

  • Calling the vector layer’s getFeatures on pointerMove and olClick returns a Promise resolving to the topmost feature at that pixel.
  • OpenLayers backs layer.getFeatures on vector layers with an off-screen hit-detection image rendered at half resolution for speed.
  • Matched features are also added to a lightweight second vector layer that draws a crisp white highlight border.
  • Categorical fills use a flat match expression on code, and event.dragging skips hit tests while panning.

Pitfalls

  • Because layer.getFeatures rasterises its internal hit map at half resolution, tiny 1-pixel islands or razor-thin boundary corners are slightly coarser than map.forEachFeatureAtPixel—choose forEachFeatureAtPixel when exact sub-pixel vertex precision is mandatory.
  • Always short-circuit highlight updates when the newly detected feature equals the already highlighted feature (highlight check), since pointermove fires dozens of times inside the same polygon before crossing a border.

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.