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.

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.tsimport { 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;
});
}
} 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.
hitdetect-vector.react.tsximport { useRef, useState } from 'react';
import OLFeature from 'ol/Feature.js';
import type OLVectorLayer from 'ol/layer/Vector.js';
import type MapBrowserEvent from 'ol/MapBrowserEvent.js';
import type OLVectorSource from 'ol/source/Vector.js';
import type { FlatStyle } from 'ol/style/flat.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
GeoJSONSource,
Map,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
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',
];
const fillStyle: FlatStyle = { 'fill-color': FILL };
const highlightStyle: FlatStyle = { 'stroke-color': 'rgba(255, 255, 255, 0.7)', 'stroke-width': 2 };
/** Voivodeships found under the pointer with the layer's hit detection, highlighted and named on hover and click. */
export function HitdetectVector() {
const [info, setInfo] = useState('–');
const layers = useRef<OLVectorLayer>(null);
const overlay = useRef<OLVectorSource>(null);
const highlight = useRef<OLFeature | undefined>(undefined);
const show = (event: MapBrowserEvent) => {
if (event.dragging) return;
void layers.current?.getFeatures(event.pixel).then((features) => {
const feature = features.find((candidate) => candidate instanceof OLFeature);
setInfo(feature ? `${feature.get('name')}: ${feature.get('code')}` : '–');
if (feature === highlight.current) return;
const source = overlay.current;
if (highlight.current) source?.removeFeature(highlight.current);
if (feature) source?.addFeature(feature);
highlight.current = feature;
});
};
return (
<>
<Map height="480px" onPointerMove={show} onClick={show}>
<DefaultInteractions />
<DefaultControls />
<View zoom={6}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<VectorLayer ref={layers} background="#1a2b39" style={fillStyle}>
<GeoJSONSource url="assets/poland/voivodeships.geojson" />
</VectorLayer>
<VectorLayer style={highlightStyle}>
<VectorSource ref={overlay} />
</VectorLayer>
</Map>
<div className="example-controls">
<p className="example-hint">Move the pointer over a voivodeship or click it.</p>
<span>
Voivodeship <output>{info}</output>
</span>
</div>
</>
);
}How the React version works
Voivodeships found under the pointer with the layer's hit detection, highlighted in an overlay layer and named on hover and click; nothing happens while the map 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-geojson> with the voivodeships | <GeoJSONSource> |
(pointerMove) and (olClick) with viewChild of the layers | onPointerMove and onClick on Map with useRef of the voivodeships and overlay layers |
the highlighted feature in a field, the name in a signal | the feature in a useRef, because it changes only the overlay, and the name in useState |
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
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
getFeaturesonpointerMoveandolClickreturns 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
matchexpression oncode, andevent.draggingskips 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 (
highlightcheck), since pointermove fires dozens of times inside the same polygon before crossing a border.
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.