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.

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.tsimport 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.tsimport { 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);
}
} 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.
webgl-vector-layer.react.tsximport { useRef, useState } from 'react';
import type OLMap from 'ol/Map.js';
import type MapBrowserEvent from 'ol/MapBrowserEvent.js';
import type { Pixel } from 'ol/pixel.js';
import TopoJSON from 'ol/format/TopoJSON.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
Map,
OSMSource,
VectorSource,
View,
} from 'cc-openlayers/react';
import { WebGLTileLayer, WebGLVectorLayer } from 'cc-openlayers/react/webgl';
import { districtStyle } from './webgl-vector-layer.shared';
const format = new TopoJSON();
/**
* 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.
*/
export function WebglVectorLayer() {
/** The name of the district under the pointer. */
const [info, setInfo] = useState(' ');
const [highlightedId, setHighlightedId] = useState<number | string>(-1);
const map = useRef<OLMap>(null);
const displayFeatureInfo = (pixel: Pixel) => {
const feature = map.current?.forEachFeatureAtPixel(pixel, (hit) => hit);
setInfo(feature?.get('name') || ' ');
setHighlightedId(feature?.getId() ?? -1);
};
const move = (event: MapBrowserEvent) => {
if (event.dragging) {
return;
}
displayFeatureInfo(event.pixel);
};
return (
<>
<Map ref={map} height="480px" onPointerMove={move} onClick={(event) => displayFeatureInfo(event.pixel)}>
<DefaultInteractions />
<DefaultControls />
<View zoom={11}>
<Coordinate x={19.98} y={50.06} srid="EPSG:4326" />
</View>
<WebGLTileLayer>
<OSMSource />
</WebGLTileLayer>
<WebGLVectorLayer style={districtStyle} variables={{ highlightedId }}>
<VectorSource
url="assets/krakow/districts.topojson"
format={format}
attributions='Districts © <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
/>
</WebGLVectorLayer>
</Map>
<div className="example-controls">
<p>{info}</p>
</div>
</>
);
}webgl-vector-layer.shared.tsimport 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,
},
},
];How the React version works
Kraków's eighteen districts drawn by a WebGL vector layer over a WebGL base map, coloured by id and labelled; the district under the pointer is highlighted through a style variable and named.
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. OpenLayers draws the tiles with WebGL; the style expressions run on the GPU in both versions. Both versions import the district style from the example's .shared.ts file, so the logic exists once.
From Angular to React
| Angular | React |
|---|---|
<aol-layer-webglvector [style] [variables]> | <WebGLVectorLayer style variables> |
(pointerMove) and (olClick) with viewChild of the map | onPointerMove and onClick on Map with useRef<OLMap> for forEachFeatureAtPixel |
signals of the name and the highlighted id | 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
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, anelse: truecategorical rule and a label rule. - Categorical
colorevaluatesmatchover['%', ['round', ['id']], 6], tinted separately for strokes ([220, 220, 220]) and 0.6-alpha fills. displayFeatureInfoqueriesforEachFeatureAtPixeland pusheshighlightedIdthrough[variables]without touching feature properties.- Districts load from
assets/krakow/districts.topojson(new TopoJSON()) aboveaol-source-osminaol-layer-webgltile.
Pitfalls
- Fragment shaders evaluate fill/stroke colours from vertex values interpolated across triangles, where GPU floating-point imprecision can turn integer ID
4into 3.999999—wrap the feature id in['round', ['id']]inside fragment colourmatchexpressions (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.
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.