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.

Kraków and neighbouring municipalities drawn from local vector tiles, with a municipal boundary highlighted.
A screenshot of the example. Boundaries: Państwowy Rejestr Granic (PRG), Główny Urząd Geodezji i Kartografii.

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.ts
import 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.ts
import {
  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();
  }
}

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.

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.