Raster, GeoTIFF and WebGL · Angular, React and OpenLayers
Flooding the terrain up to a water level
Simulate interactive terrain flooding around Kraków from non-interpolated Terrarium DEM tiles in an OpenLayers RasterSource with live readouts.

What this example shows
Over OpenStreetMap of Kraków and the Vistula valley at zoom 11, a Water level slider (180 to 260 m above sea level, starting at 200 m) floods every lowland area at or below the chosen elevation in translucent light blue, paired with a live pointer elevation readout (– before interaction) and quick-jump buttons for four regional towns.
When you need it
River-basin flood planners, reservoir engineers, coastal resilience portals and geography educators use interactive water-level sliders to visualise inundation zones immediately in the browser.
Decoding global RGB-encoded elevation tiles client-side eliminates server-side flood-polygon precomputation for arbitrary water levels.
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.
sea-level.shared.tsexport const ATTRIBUTIONS =
'Elevation: <a href="https://github.com/tilezen/joerd/blob/master/docs/attribution.md" target="_blank">Terrain Tiles</a>';
export interface Place {
name: string;
lon: number;
lat: number;
}
/** The Vistula valley and the neighbouring towns, which the buttons move the map to. */
export const PLACES: Place[] = [
{ name: 'Kraków', lon: 19.9368, lat: 50.0614 },
{ name: 'Tarnów', lon: 20.9877, lat: 50.0121 },
{ name: 'Oświęcim', lon: 19.2238, lat: 50.0343 },
{ name: 'Nowy Sącz', lon: 20.6877, lat: 49.6249 },
];
export interface FloodData {
level: number;
}
/**
* Paints the pixels whose elevation is at or below the water level light blue and hides the others. The tiles
* are Terrarium-encoded: elevation in metres is `R * 256 + G + B / 256 - 32768`.
*/
export function flood(pixels: number[][], data: FloodData): number[] {
const pixel = pixels[0];
if (pixel[3]) {
const height = pixel[0] * 256 + pixel[1] + pixel[2] / 256 - 32768;
if (height <= data.level) {
pixel[0] = 134;
pixel[1] = 203;
pixel[2] = 249;
pixel[3] = 255;
} else {
pixel[3] = 0;
}
}
return pixel;
}
/** The elevation in metres a tile pixel encodes (see `flood`), rounded; undefined where the pixel is transparent. */
export function elevationOf(pixel: ArrayLike<number> | undefined): number | undefined {
return pixel?.[3] ? Math.round(pixel[0] * 256 + pixel[1] + pixel[2] / 256 - 32768) : undefined;
}sea-level.tsimport { ChangeDetectionStrategy, Component, computed, signal, viewChild } from '@angular/core';
import type { MapBrowserEvent } from 'ol';
import { fromLonLat } from 'ol/proj';
import type { RasterSourceEvent } from 'ol/source/Raster';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerImageComponent,
LayerTileComponent,
MapComponent,
SourceOsmComponent,
SourceRasterComponent,
SourceXYZComponent,
ViewComponent,
} from 'cc-openlayers';
import { ATTRIBUTIONS, elevationOf, flood, type FloodData, PLACES, type Place } from './sea-level.shared';
/**
* A raster source that floods the terrain below the chosen elevation, read from Terrarium elevation tiles without
* interpolation, as blending neighbouring pixels would mix the colours that encode their heights; the elevation
* under the pointer is read back from its input.
*/
@Component({
selector: 'app-sea-level',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerImageComponent,
LayerTileComponent,
MapComponent,
SourceOsmComponent,
SourceRasterComponent,
SourceXYZComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px" (pointerMove)="showElevation($event)" (singleClick)="showElevation($event)">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="11">
<aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
</aol-view>
<aol-layer-tile><aol-source-osm /></aol-layer-tile>
<aol-layer-image [opacity]="0.6">
<aol-source-raster [operation]="operation" (beforeOperations)="beforeOperations($event)">
<aol-source-xyz
url="https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
[attributions]="attributions"
crossOrigin="anonymous"
[interpolate]="false"
[maxZoom]="15"
/>
</aol-source-raster>
</aol-layer-image>
</aol-map>
<div class="example-controls">
<span>
Elevation at pointer <output>{{ elevation() }}</output>
</span>
<label>
Water level
<input
type="range"
min="180"
max="260"
[value]="level()"
(input)="level.set(number($event)); raster().instance.changed()"
/>
<output>{{ level() }}</output>
m above sea level
</label>
@for (place of places; track place.name) {
<button type="button" (click)="goTo(place)">{{ place.name }}</button>
}
</div>
`,
})
export class SeaLevel {
readonly level = signal(200);
protected readonly metres = signal<number | undefined>(undefined);
protected readonly elevation = computed(() => {
const metres = this.metres();
return metres === undefined ? '–' : `${metres} m`;
});
protected readonly attributions = ATTRIBUTIONS;
protected readonly operation = flood;
protected readonly places = PLACES;
private readonly map = viewChild.required(MapComponent);
protected readonly raster = viewChild.required(SourceRasterComponent);
/** Hands the water level to the pixel operation. */
protected beforeOperations(event: Pick<RasterSourceEvent, 'data'>): void {
const data: FloodData = event.data;
data.level = this.level();
}
/** The elevation under the pointer or a click, decoded as in `flood` from the tile pixel the operation gets there. */
protected showElevation(event: MapBrowserEvent): void {
const pixel = this.raster().instance.getData(event.coordinate)?.[0];
this.metres.set(elevationOf(pixel));
}
protected goTo(place: Place): void {
const view = this.map().instance.getView();
view.setCenter(fromLonLat([place.lon, place.lat]));
view.setZoom(11);
}
protected number(event: Event): number {
return (event.target as HTMLInputElement).valueAsNumber;
}
} 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.
sea-level.react.tsximport { useRef, useState, type ChangeEvent } from 'react';
import type { MapBrowserEvent } from 'ol';
import type OLMap from 'ol/Map.js';
import { fromLonLat } from 'ol/proj.js';
import type Raster from 'ol/source/Raster.js';
import type { Operation, RasterSourceEvent } from 'ol/source/Raster.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
ImageLayer,
Map,
OSMSource,
RasterSource,
TileLayer,
View,
XYZSource,
} from 'cc-openlayers/react';
import { ATTRIBUTIONS, elevationOf, flood, type FloodData, PLACES, type Place } from './sea-level.shared';
/**
* A raster source that floods the terrain below the chosen elevation, read from Terrarium elevation tiles without
* interpolation, as blending neighbouring pixels would mix the colours that encode their heights; the elevation
* under the pointer is read back from its input.
*/
export function SeaLevel() {
const [level, setLevel] = useState(200);
const [metres, setMetres] = useState<number | undefined>(undefined);
const map = useRef<OLMap>(null);
const raster = useRef<Raster>(null);
const elevation = metres === undefined ? '–' : `${metres} m`;
/** Hands the water level to the pixel operation. */
const beforeOperations = (event: Pick<RasterSourceEvent, 'data'>): void => {
const data: FloodData = event.data;
data.level = level;
};
/** The elevation under the pointer or a click, decoded as in `flood` from the tile pixel the operation gets there. */
const showElevation = (event: MapBrowserEvent): void => {
const pixel = raster.current?.getData(event.coordinate)?.[0] as ArrayLike<number> | undefined;
setMetres(elevationOf(pixel));
};
const goTo = (place: Place): void => {
const view = map.current?.getView();
view?.setCenter(fromLonLat([place.lon, place.lat]));
view?.setZoom(11);
};
return (
<>
<Map ref={map} height="480px" onPointerMove={showElevation} onSingleClick={showElevation}>
<DefaultInteractions />
<DefaultControls />
<View zoom={11}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
<ImageLayer opacity={0.6}>
<RasterSource ref={raster} operation={flood as Operation} onBeforeOperations={beforeOperations}>
<XYZSource
url="https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
attributions={ATTRIBUTIONS}
crossOrigin="anonymous"
interpolate={false}
maxZoom={15}
/>
</RasterSource>
</ImageLayer>
</Map>
<div className="example-controls">
<span>
Elevation at pointer <output>{elevation}</output>
</span>
<label>
Water level
<input
type="range"
min="180"
max="260"
value={level}
onChange={(event: ChangeEvent<HTMLInputElement>) => {
setLevel(event.target.valueAsNumber);
raster.current?.changed();
}}
/>
<output>{level}</output>m above sea level
</label>
{PLACES.map((place) => (
<button key={place.name} type="button" onClick={() => goTo(place)}>
{place.name}
</button>
))}
</div>
</>
);
}sea-level.shared.tsexport const ATTRIBUTIONS =
'Elevation: <a href="https://github.com/tilezen/joerd/blob/master/docs/attribution.md" target="_blank">Terrain Tiles</a>';
export interface Place {
name: string;
lon: number;
lat: number;
}
/** The Vistula valley and the neighbouring towns, which the buttons move the map to. */
export const PLACES: Place[] = [
{ name: 'Kraków', lon: 19.9368, lat: 50.0614 },
{ name: 'Tarnów', lon: 20.9877, lat: 50.0121 },
{ name: 'Oświęcim', lon: 19.2238, lat: 50.0343 },
{ name: 'Nowy Sącz', lon: 20.6877, lat: 49.6249 },
];
export interface FloodData {
level: number;
}
/**
* Paints the pixels whose elevation is at or below the water level light blue and hides the others. The tiles
* are Terrarium-encoded: elevation in metres is `R * 256 + G + B / 256 - 32768`.
*/
export function flood(pixels: number[][], data: FloodData): number[] {
const pixel = pixels[0];
if (pixel[3]) {
const height = pixel[0] * 256 + pixel[1] + pixel[2] / 256 - 32768;
if (height <= data.level) {
pixel[0] = 134;
pixel[1] = 203;
pixel[2] = 249;
pixel[3] = 255;
} else {
pixel[3] = 0;
}
}
return pixel;
}
/** The elevation in metres a tile pixel encodes (see `flood`), rounded; undefined where the pixel is transparent. */
export function elevationOf(pixel: ArrayLike<number> | undefined): number | undefined {
return pixel?.[3] ? Math.round(pixel[0] * 256 + pixel[1] + pixel[2] / 256 - 32768) : undefined;
}How the React version works
Terrain below a chosen elevation flooded by a raster source reading Terrarium elevation tiles, over OpenStreetMap; the elevation under the pointer is shown and buttons move the map to towns.
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. Both versions import the attribution, the towns, flood and elevationOf, which turns a pixel into a height, from the example's .shared.ts file, so the logic exists once. The raster source turns the operation into source text for its worker. The elevation tiles are read with nearest-pixel sampling, because their colours encode heights that must not be blended.
From Angular to React
| Angular | React |
|---|---|
<aol-layer-image> with <aol-source-raster [operation] (beforeOperations)> around the elevation tiles | <ImageLayer> with <RasterSource operation onBeforeOperations> around them |
(pointerMove) and (singleClick) reading getData | onPointerMove and onSingleClick on Map with useRef<OLMap> |
viewChild of the raster source and changed() after a control | ref on RasterSource (useRef) and changed() in the handler |
signals of the level and the elevation | 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
An aol-layer-image ([opacity]="0.6") wraps aol-source-raster over aol-source-xyz pointing at AWS Terrarium PNG tiles (crossOrigin="anonymous", [maxZoom]="15", and critically [interpolate]="false"). Worker function flood decodes each pixel via R * 256 + G + B / 256 - 32768 metres—painting pixels <= data.level light blue and higher ground transparent.
Scrubbing the slider updates level and calls changed() on the raster source (passing data.level via (beforeOperations)), while showElevation decodes the rounded height under the pointer from getData(event.coordinate).
How it works
flooddecodes Terrarium RGB bytes (R * 256 + G + B / 256 - 32768m) and colours terrain at or belowdata.levellight blue.[interpolate]="false"enforces nearest-neighbour tile sampling so RGB-encoded byte channels are never blended across pixel boundaries.- Dragging the 180–260 m slider (initial
200m) updatesleveland invokeschanged()onaol-source-raster. showElevationdecodes raw input height fromgetData(event.coordinate)on pointer move and click, alongside four town preset buttons.
Pitfalls
- Leaving bilinear interpolation enabled on RGB-encoded Terrarium tiles blends high-order
Rand low-orderG/Bchannels between adjacent pixels (for instance turning the boundary between 255 m and 256 m into false 128 m or 384 m rings)—always set[interpolate]="false". - Because the Terrarium pyramid stops at
[maxZoom]="15", zooming closer than level 15 enlarges level-15 elevation pixels cleanly.
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.