Raster, GeoTIFF and WebGL · Angular, React and OpenLayers

Polygons in a WebGL vector layer

Render Kraków’s 18 districts on the GPU with an OpenLayers WebGLVectorLayer and highlight hovered polygons via style variables without rebuilds.

OpenStreetMap of Kraków with its eighteen districts in six colours, each labelled, Stare Miasto highlighted white under the pointer and named below the map.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Over a GPU-rendered OpenStreetMap backdrop of Kraków at zoom 11, all eighteen city districts loaded from assets/krakow/districts.topojson render in a six-colour categorical palette with district labels—highlighting whichever district is hovered or clicked in crisp white via a uniform style variable and naming it below.

When you need it

Cadastral maps, zoning plans and statistical portals containing tens of thousands of polygons stutter on 2D Canvas during fast pans or hover highlights.

WebGLVectorLayer tessellates polygons into GPU vertex buffers once and updates hover highlights in zero-cost shader uniforms without regenerating geometry buffers.

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.

webgl-vector-layer.shared.ts
import type { FlatStyleLike } from 'ol/style/flat.js';

/**
 * The colour of a district, picked by its number: six colours in turn. The number is rounded first: fill and stroke
 * colours are worked out per pixel from a value the GPU interpolates across each triangle, which some GPUs return a
 * hair off the whole number, and the exact match would then fall back to the last colour.
 */
const color = [
  'match',
  ['%', ['round', ['id']], 6],
  0,
  '#66c2a5',
  1,
  '#fc8d62',
  2,
  '#8da0cb',
  3,
  '#e78ac3',
  4,
  '#a6d854',
  '#ffd92f',
];

/** The flat style of the districts: highlighted by the `highlightedId` variable, coloured by id and labelled by name. */
export const districtStyle: FlatStyleLike = [
  {
    filter: ['==', ['var', 'highlightedId'], ['id']],
    style: {
      'stroke-color': 'white',
      'stroke-width': 3,
      'stroke-offset': -1,
      'fill-color': [255, 255, 255, 0.4],
    },
  },
  {
    else: true,
    style: {
      'stroke-color': ['*', color, [220, 220, 220]],
      'stroke-width': 2,
      'stroke-offset': -1,
      'fill-color': ['*', color, [255, 255, 255, 0.6]],
    },
  },
  {
    style: {
      'text-value': ['coalesce', ['get', 'name'], 'unknown'],
      'text-font': 'bold 12px "Open Sans", "Arial Unicode MS", sans-serif',
      'text-fill-color': 'rgb(0,0,0)',
      'text-stroke-color': 'rgba(255, 255, 255, 0.8)',
      'text-stroke-width': 2,
      'text-overflow': false,
    },
  },
];
webgl-vector-layer.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import type { Pixel } from 'ol/pixel';
import TopoJSON from 'ol/format/TopoJSON';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  MapComponent,
  SourceOsmComponent,
  SourceVectorComponent,
  ViewComponent,
} from 'cc-openlayers';
import { LayerWebGLTileComponent, LayerWebGLVectorComponent } from 'cc-openlayers/webgl';
import { districtStyle } from './webgl-vector-layer.shared';

/**
 * Kraków's eighteen districts drawn by a WebGL vector layer over OpenStreetMap drawn with WebGL: each district is
 * coloured and filtered by its id (its number), labelled by name, and the one under the pointer is highlighted
 * through a style variable.
 */
@Component({
  selector: 'app-webgl-vector-layer',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerWebGLTileComponent,
    LayerWebGLVectorComponent,
    MapComponent,
    SourceOsmComponent,
    SourceVectorComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px" (pointerMove)="move($event)" (olClick)="displayFeatureInfo($event.pixel)">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="11">
        <aol-coordinate [x]="19.98" [y]="50.06" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-webgltile><aol-source-osm /></aol-layer-webgltile>
      <aol-layer-webglvector [style]="style" [variables]="{ highlightedId: highlightedId() }">
        <aol-source-vector
          url="assets/krakow/districts.topojson"
          [format]="format"
          attributions='Districts © <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
        />
      </aol-layer-webglvector>
    </aol-map>
    <div class="example-controls">
      <p>{{ info() }}</p>
    </div>
  `,
})
export class WebglVectorLayer {
  protected readonly style = districtStyle;
  protected readonly format = new TopoJSON();
  /** The name of the district under the pointer. */
  protected readonly info = signal(' ');
  protected readonly highlightedId = signal<number | string>(-1);
  private readonly map = viewChild.required(MapComponent);

  protected move(event: MapBrowserEvent): void {
    if (event.dragging) {
      return;
    }
    this.displayFeatureInfo(event.pixel);
  }

  protected displayFeatureInfo(pixel: Pixel): void {
    const feature = this.map().instance.forEachFeatureAtPixel(pixel, function (feature) {
      return feature;
    });
    this.info.set(feature?.get('name') || ' ');
    this.highlightedId.set(feature?.getId() ?? -1);
  }
}

Architecture and OpenLayers mechanics

aol-layer-webglvector loads assets/krakow/districts.topojson via new TopoJSON(). Its three-rule flat style draws a white highlight border where ['==', ['var', 'highlightedId'], ['id']], falls back via else: true to a six-colour match expression on ['%', ['round', ['id']], 6], and renders district labels.

On (pointerMove) (ignoring drags) and (olClick), displayFeatureInfo resolves the district via forEachFeatureAtPixel and updates highlightedId inside [variables].

How it works

  • Three rules combine a ['==', ['var', 'highlightedId'], ['id']] highlight rule, an else: true categorical rule and a label rule.
  • Categorical color evaluates match over ['%', ['round', ['id']], 6], tinted separately for strokes ([220, 220, 220]) and 0.6-alpha fills.
  • displayFeatureInfo queries forEachFeatureAtPixel and pushes highlightedId through [variables] without touching feature properties.
  • Districts load from assets/krakow/districts.topojson (new TopoJSON()) above aol-source-osm in aol-layer-webgltile.

Pitfalls

  • Fragment shaders evaluate fill/stroke colours from vertex values interpolated across triangles, where GPU floating-point imprecision can turn integer ID 4 into 3.999999—wrap the feature id in ['round', ['id']] inside fragment colour match expressions (vertex-stage rule filters use exact values and need no rounding).
  • Always drive hover state through [variables] rather than calling feature.set(...): mutating a feature property invalidates the vector source and makes WebGL retessellate that feature and re-upload the buffers of the whole batch.

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.