Interactions · Angular, React and OpenLayers
Select vector-tile features
Highlight single or multiple polygons across tile seams in OpenLayers vector tiles on click or hover using stable feature IDs and selection layers.

What this example shows
Municipalities in the Kraków metropolitan area are rendered from local vector tiles alongside a mode selector offering single-click selection, multi-select accumulation and live pointer-hover highlighting. Clicking or hovering over a large municipality highlights its entire administrative boundary cleanly—even where the polygon is sliced across four or more adjacent tiles.
Clicking empty space clears the active selection, and switching interaction modes discards stale asynchronous hit-detection callbacks so highlighted polygons always match the latest pointer input.
When you need it
Regional analytics dashboards, electoral maps, cadastral portals and zoning explorers use vector tiles for fast rendering of thousands of polygons while still requiring crisp, whole-feature selection and hover feedback.
Unlike GeoJSON vector sources—where one municipality is a single in-memory Feature object—vector tile pyramids slice large polygons into separate RenderFeature fragments per tile. Naively styling only the clicked fragment highlights a rectangular wedge of a commune and leaves its remaining tiles unselected.
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.
vector-tile-selection.html<aol-map height="480px" ariaLabel="Kraków municipality map">
<aol-interaction-default />
<aol-control-defaults />
<aol-view projection="EPSG:4326" [zoom]="10">
<aol-coordinate [x]="center[0]" [y]="center[1]" srid="EPSG:4326" />
</aol-view>
<aol-layer-vectortile background="#d1d1d1" [style]="municipalityStyle">
<aol-source-ogcvectortile
[url]="tilesetUrl"
projection="EPSG:4326"
attributions="Boundaries: PRG, Główny Urząd Geodezji i Kartografii"
>
<aol-format-mvt />
</aol-source-ogcvectortile>
</aol-layer-vectortile>
<aol-layer-vectortile [renderMode]="'vector'" [style]="selectionStyle" />
</aol-map>
<div class="example-controls">
<fieldset>
<legend>Selection mode</legend>
<label
><input
type="radio"
name="vector-tile-selection-angular"
value="single"
[checked]="mode() === 'single'"
(change)="setMode('single')"
/>
Single select</label
>
<label
><input
type="radio"
name="vector-tile-selection-angular"
value="multiple"
[checked]="mode() === 'multiple'"
(change)="setMode('multiple')"
/>
Multiple select</label
>
<label
><input
type="radio"
name="vector-tile-selection-angular"
value="hover"
[checked]="mode() === 'hover'"
(change)="setMode('hover')"
/>
Select on hover</label
>
</fieldset>
<output role="status" aria-live="polite">Selected: {{ selectedCount() }}</output>
</div>vector-tile-selection.scss.example-controls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 1rem;
}
fieldset {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.75rem;
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
legend {
margin-right: 0.75rem;
font-weight: 600;
}
label {
display: inline-flex;
align-items: center;
gap: 0.35rem;
cursor: pointer;
}
[role='status'] {
font-variant-numeric: tabular-nums;
}vector-tile-selection.shared.tsimport type { FeatureLike } from 'ol/Feature.js';
import Fill from 'ol/style/Fill.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';
import type { VectorTileSelectionId } from 'cc-openlayers/core';
export const municipalityTilesetPath = 'assets/krakow/municipality-tiles/WorldCRS84Quad.json';
export const municipalityCenter = [19.937, 50.0614] as const;
const selectedMunicipalityStyle = new Style({
fill: new Fill({ color: 'rgba(200, 20, 20, 0.4)' }),
stroke: new Stroke({ color: 'rgba(200, 20, 20, 0.8)', width: 2 }),
});
export function municipalitySelectionStyle(
feature: FeatureLike,
selectedIds: Set<VectorTileSelectionId>
): Style | undefined {
const id = feature.getId();
return id !== undefined && selectedIds.has(id) ? selectedMunicipalityStyle : undefined;
}vector-tile-selection.tsimport {
AfterViewInit,
ChangeDetectionStrategy,
Component,
inject,
NgZone,
OnDestroy,
signal,
viewChild,
viewChildren,
} from '@angular/core';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
FormatMVTComponent,
LayerVectorTileComponent,
MapComponent,
SourceOGCVectorTileComponent,
ViewComponent,
} from 'cc-openlayers';
import {
connectVectorTileSelection,
type VectorTileSelectionController,
type VectorTileSelectionId,
type VectorTileSelectionMode,
} from 'cc-openlayers/core';
import type { FeatureLike } from 'ol/Feature.js';
import { style as municipalityStyle } from '../ogc-vector-tiles-geographic/ogc-vector-tiles-geographic.shared';
import {
municipalityCenter,
municipalitySelectionStyle,
municipalityTilesetPath,
} from './vector-tile-selection.shared';
/** Selects municipalities from the local geographic vector tiles by their stable feature ids. */
@Component({
selector: 'app-vector-tile-selection',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
FormatMVTComponent,
LayerVectorTileComponent,
MapComponent,
SourceOGCVectorTileComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './vector-tile-selection.html',
styleUrl: './vector-tile-selection.scss',
})
export class VectorTileSelection implements AfterViewInit, OnDestroy {
readonly selectedCount = signal(0);
readonly mode = signal<VectorTileSelectionMode>('single');
protected readonly center = municipalityCenter;
protected readonly tilesetUrl = new URL(municipalityTilesetPath, document.baseURI).href;
protected readonly municipalityStyle = municipalityStyle;
protected readonly selectedIds = new Set<VectorTileSelectionId>();
protected readonly selectionStyle = (feature: FeatureLike) => municipalitySelectionStyle(feature, this.selectedIds);
private readonly map = viewChild.required(MapComponent);
private readonly layers = viewChildren(LayerVectorTileComponent);
private readonly zone = inject(NgZone);
private selection?: VectorTileSelectionController;
ngAfterViewInit(): void {
const [sourceLayer, selectionLayer] = this.layers();
const source = sourceLayer?.instance.getSource();
if (!sourceLayer || !selectionLayer || !source) return;
selectionLayer.instance.setSource(source);
this.selection = connectVectorTileSelection(
this.map().instance,
sourceLayer.instance,
selectionLayer.instance,
this.selectedIds,
(count) => this.zone.run(() => this.selectedCount.set(count))
);
}
setMode(mode: VectorTileSelectionMode): void {
this.mode.set(mode);
this.selection?.setMode(mode);
}
ngOnDestroy(): void {
this.selection?.dispose();
}
} 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.
vector-tile-selection.react.tsximport { useCallback, useEffect, useRef, useState } from 'react';
import type { FeatureLike } from 'ol/Feature.js';
import type OLMap from 'ol/Map.js';
import type OLVectorTileLayer from 'ol/layer/VectorTile.js';
import type OGCVectorTile from 'ol/source/OGCVectorTile.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
Map,
OGCVectorTileSource,
useMVTFormat,
VectorTileLayer,
View,
} from 'cc-openlayers/react';
import {
connectVectorTileSelection,
type VectorTileSelectionController,
type VectorTileSelectionId,
type VectorTileSelectionMode,
} from 'cc-openlayers/core';
import { style as municipalityStyle } from '../ogc-vector-tiles-geographic/ogc-vector-tiles-geographic.shared';
import {
municipalityCenter,
municipalitySelectionStyle,
municipalityTilesetPath,
} from './vector-tile-selection.shared';
export function VectorTileSelectionReact() {
const [mode, setMode] = useState<VectorTileSelectionMode>('single');
const [selectedCount, setSelectedCount] = useState(0);
const map = useRef<OLMap>(null);
const sourceLayer = useRef<OLVectorTileLayer | null>(null);
const selectionLayer = useRef<OLVectorTileLayer | null>(null);
const tileSource = useRef<OGCVectorTile<FeatureLike> | null>(null);
const selectedIds = useRef(new Set<VectorTileSelectionId>());
const selection = useRef<VectorTileSelectionController | null>(null);
const connected = useRef<{
map: OLMap;
sourceLayer: OLVectorTileLayer;
selectionLayer: OLVectorTileLayer;
source: OGCVectorTile<FeatureLike>;
} | null>(null);
const format = useMVTFormat();
const selectionStyle = useCallback(
(feature: FeatureLike) => municipalitySelectionStyle(feature, selectedIds.current),
[]
);
const tilesetUrl = new URL(municipalityTilesetPath, document.baseURI).href;
const connect = useCallback(() => {
const mapInstance = map.current;
const baseLayer = sourceLayer.current;
const highlightLayer = selectionLayer.current;
const source = tileSource.current;
if (!mapInstance || !baseLayer || !highlightLayer || !source) {
selection.current?.dispose();
selection.current = null;
connected.current = null;
return;
}
const previous = connected.current;
if (
previous?.map === mapInstance &&
previous.sourceLayer === baseLayer &&
previous.selectionLayer === highlightLayer &&
previous.source === source
) {
return;
}
selection.current?.dispose();
highlightLayer.setSource(source);
selection.current = connectVectorTileSelection(
mapInstance,
baseLayer,
highlightLayer,
selectedIds.current,
setSelectedCount
);
connected.current = {
map: mapInstance,
sourceLayer: baseLayer,
selectionLayer: highlightLayer,
source,
};
}, []);
const bindMap = useCallback(
(value: OLMap | null) => {
map.current = value;
connect();
},
[connect]
);
const bindSourceLayer = useCallback(
(value: OLVectorTileLayer | null) => {
sourceLayer.current = value;
connect();
},
[connect]
);
const bindSelectionLayer = useCallback(
(value: OLVectorTileLayer | null) => {
selectionLayer.current = value;
connect();
},
[connect]
);
const bindTileSource = useCallback(
(value: OGCVectorTile<FeatureLike> | null) => {
tileSource.current = value;
connect();
},
[connect]
);
useEffect(() => {
connect();
return () => {
selection.current?.dispose();
selection.current = null;
connected.current = null;
};
}, [connect]);
const changeMode = (nextMode: VectorTileSelectionMode) => {
selection.current?.setMode(nextMode);
setMode(nextMode);
};
return (
<>
<Map height="480px" ref={bindMap} ariaLabel="Kraków municipality map">
<DefaultInteractions />
<DefaultControls />
<View projection="EPSG:4326" zoom={10}>
<Coordinate x={municipalityCenter[0]} y={municipalityCenter[1]} srid="EPSG:4326" />
</View>
<VectorTileLayer ref={bindSourceLayer} background="#d1d1d1" style={municipalityStyle}>
<OGCVectorTileSource
ref={bindTileSource}
url={tilesetUrl}
projection="EPSG:4326"
attributions="Boundaries: PRG, Główny Urząd Geodezji i Kartografii"
format={format}
/>
</VectorTileLayer>
<VectorTileLayer ref={bindSelectionLayer} renderMode="vector" style={selectionStyle} />
</Map>
<div className="example-controls">
<fieldset>
<legend>Selection mode</legend>
<label>
<input
type="radio"
name="vector-tile-selection-react"
value="single"
checked={mode === 'single'}
onChange={() => changeMode('single')}
/>
Single select
</label>
<label>
<input
type="radio"
name="vector-tile-selection-react"
value="multiple"
checked={mode === 'multiple'}
onChange={() => changeMode('multiple')}
/>
Multiple select
</label>
<label>
<input
type="radio"
name="vector-tile-selection-react"
value="hover"
checked={mode === 'hover'}
onChange={() => changeMode('hover')}
/>
Select on hover
</label>
</fieldset>
<output role="status" aria-live="polite">
Selected: {selectedCount}
</output>
</div>
</>
);
}vector-tile-selection.shared.tsimport type { FeatureLike } from 'ol/Feature.js';
import Fill from 'ol/style/Fill.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';
import type { VectorTileSelectionId } from 'cc-openlayers/core';
export const municipalityTilesetPath = 'assets/krakow/municipality-tiles/WorldCRS84Quad.json';
export const municipalityCenter = [19.937, 50.0614] as const;
const selectedMunicipalityStyle = new Style({
fill: new Fill({ color: 'rgba(200, 20, 20, 0.4)' }),
stroke: new Stroke({ color: 'rgba(200, 20, 20, 0.8)', width: 2 }),
});
export function municipalitySelectionStyle(
feature: FeatureLike,
selectedIds: Set<VectorTileSelectionId>
): Style | undefined {
const id = feature.getId();
return id !== undefined && selectedIds.has(id) ? selectedMunicipalityStyle : undefined;
}How the React version works
Select Kraków or a neighbouring municipality from the existing local WorldCRS84Quad vector tiles. Single selection replaces the chosen feature, multiple selection accumulates clicked IDs, and hover selection follows the pointer. An empty hit clears the selection. Both versions begin at Rynek Główny and retain the PRG/GUGiK attribution. The fixture generator traces the tiles to the existing PRG municipality GeoJSON.
What both versions share
connectVectorTileSelection and its neutral types come from cc-openlayers/core; the core imports neither framework nor RxJS. It owns hit-result ordering and listener cleanup. Single and hover modes accept the latest compatible hit. Multiple mode applies click outcomes in input order, including an empty hit, even when their promises resolve in another order. Rejections preserve the selection and allow later clicks to continue. Mode changes, hover dragging and disposal invalidate incompatible pending results. The example's shared file contains only its municipality tileset path, public center and highlight style. A stable-ID set drives the highlight, so separate tile fragments of one municipality receive the same style. The highlight layer shares the base layer's source and uses vector rendering mode.
From Angular to React
| Angular | React |
|---|---|
MapComponent and LayerVectorTileComponent view queries | Stable wrapper ref callbacks |
ngAfterViewInit connects the rendered layers | Ref/effect ownership reconnects when StrictMode replaces wrapper instances |
| Signals expose mode and selected count | useState exposes mode and selected count; useRef retains the ID set |
ngOnDestroy disposes the binding | Effect/ref cleanup disposes the binding on unmount |
Who creates, updates and disposes
The existing map, layer and source wrappers own their OpenLayers objects. The example connects caller-owned layers to the core binding and supplies a style reading the selected-ID set. The core changes IDs and requests highlight redraws; it does not dispose layers or sources. It invalidates pending hit results on disposal because OpenLayers hit promises expose no abort signal.
Architecture and OpenLayers mechanics
The robust OpenLayers pattern pairs the base vector-tile layer with a lightweight second vector-tile selection layer bound to the exact same source and configured in vector render mode. Instead of tracking ephemeral tile-fragment object references, the component stores a dictionary or set of persistent feature IDs.
When pointer click or move events resolve features under the pixel, the selection state updates by stable ID and calls changed() on the selection layer. Its style function then returns a highlight stroke/fill for every visible tile fragment whose ID belongs to the selected set—reconstructing a seamless polygon highlight across tile boundaries.
How it works
- An OGC vector-tile source loads local WorldCRS84Quad tiles covering Kraków and neighbouring municipalities with persistent administrative identifiers.
- A dedicated overlay vector-tile layer shares the underlying tile source and renders only features whose IDs match the current selection state.
- An interaction selector switches cleanly between single-click replacement, additive multi-feature click selection and continuous hover tracking.
- Clicking outside municipal features clears the active set, while sequence guards ignore outdated asynchronous hit-detection promises when modes or pointer positions change rapidly.
Pitfalls
- Never store clicked RenderFeature object instances in your selection state: panning or zooming reloads tile fragments as new objects, and large polygons split across multiple tiles will highlight only partially unless matched by stable feature ID.
- Ensure your MVT or GeoJSON tile generator promotes a unique feature identifier into each vector tile feature; without unique IDs, cross-tile selection cannot correlate fragments.
- Dispose of pointer event subscriptions and clear selection state when the map component unmounts to avoid memory leaks or stale callbacks.
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.