Styling and labels · Angular, React and OpenLayers
Custom symbols drawn once per magnitude
Pre-render crisp HiDPI lightning-bolt symbols per magnitude onto off-screen canvases with toContext and cache them across 1,130 KML earthquakes.

What this example shows
Across the Upper Silesian coal basin west of Kraków between Katowice, Rybnik and Karviná, 1,130 seismic events render as sharp custom orange lightning-bolt glyphs scaled by earthquake magnitude, tucked cleanly underneath an upper reference layer of town names.
When you need it
Domain-specific vector symbols—hazard lightning bolts, meteorological barbs, military/emergency APP-6 icons or utility valves—often come from vector coordinate geometry rather than static SVG files, yet re-stroking complex multi-vertex polygons 1,130 times on every pan frame wastes CPU.
Rasterising each distinct symbol size once onto a HiDPI off-screen <canvas> via toContext and reusing it as an Icon combines arbitrary vector geometry with sprite-sheet rendering speed.
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.
earthquake-custom-symbol.tsimport { afterNextRender, ChangeDetectionStrategy, Component, viewChild } from '@angular/core';
import { getBottomLeft, getTopRight } from 'ol/extent';
import type { FeatureLike } from 'ol/Feature';
import KML from 'ol/format/KML';
import Polygon from 'ol/geom/Polygon';
import { DEVICE_PIXEL_RATIO } from 'ol/has';
import { toContext } from 'ol/render';
import type { VectorSourceEvent } from 'ol/source/Vector';
import Fill from 'ol/style/Fill';
import Icon from 'ol/style/Icon';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceImageTileComponent,
SourceVectorComponent,
ViewComponent,
} from 'cc-openlayers';
const getSymbolOutline = (function () {
const path = [
[0, 0],
[4, 2],
[6, 0],
[10, 5],
[6, 3],
[4, 5],
[0, 0],
];
const symbolOutline = new Polygon([path]);
symbolOutline.rotate(1.2, path[0]);
return function (scale: number, offset: number) {
const outline = symbolOutline.clone();
outline.scale(scale, scale, path[0]);
const origin = getBottomLeft(outline.getExtent());
outline.translate(offset - origin[0], offset - origin[1]);
return outline;
};
})();
const styleCache: Record<number, Style> = {};
const style = function (feature: FeatureLike): Style {
const magnitude: number = feature.get('magnitude');
let style = styleCache[magnitude];
if (!style) {
// Sized for the events' density: most of them are 2 to 3 and lie within some 50 km.
const scale = 1 + (magnitude - 2);
const lineWidth = 2;
const outline = getSymbolOutline(scale, Math.ceil(lineWidth / 2));
const canvas = document.createElement('canvas');
const vectorContext = toContext(canvas.getContext('2d') as CanvasRenderingContext2D, {
size: getTopRight(outline.getExtent()).map((n) => Math.ceil(n + lineWidth / 2)),
pixelRatio: DEVICE_PIXEL_RATIO,
});
vectorContext.setStyle(
new Style({
fill: new Fill({ color: 'rgba(255, 153, 0, 0.4)' }),
stroke: new Stroke({
color: 'rgba(255, 204, 0, 0.2)',
width: 2,
}),
})
);
vectorContext.drawGeometry(outline);
style = new Style({
image: new Icon({
img: canvas,
scale: 1 / DEVICE_PIXEL_RATIO,
}),
});
styleCache[magnitude] = style;
}
return style;
};
// tremors.kml names each event by its magnitude, "M 3.4 - 1995 Mar 7".
function parseMagnitudeFromName(name: string): number {
return parseFloat(name.slice(2));
}
/**
* The seismic events around Kraków since 1978 read from a KML file, each drawn as a lightning-shaped symbol sized by
* its magnitude: the symbol is drawn once per magnitude onto a canvas with the immediate rendering API and used as the
* image of an icon.
*/
@Component({
selector: 'app-earthquake-custom-symbol',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceImageTileComponent,
SourceVectorComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="9">
<aol-coordinate [x]="19.25" [y]="50.15" srid="EPSG:4326" />
</aol-view>
<aol-layer-tile>
<aol-source-imagetile
url="https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
[maxZoom]="16"
attributions="Tiles © Esri — Esri, HERE, Garmin, © OpenStreetMap contributors, and the GIS user community"
/>
</aol-layer-tile>
<aol-layer-vector [style]="style">
<aol-source-vector
url="assets/krakow/tremors.kml"
[format]="format"
attributions="Seismic events: U.S. Geological Survey"
/>
</aol-layer-vector>
<aol-layer-tile>
<aol-source-imagetile
url="https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer/tile/{z}/{y}/{x}"
[maxZoom]="16"
/>
</aol-layer-tile>
</aol-map>
`,
})
export class EarthquakeCustomSymbol {
protected readonly style = style;
protected readonly format = new KML({
extractStyles: false,
});
private readonly source = viewChild.required(SourceVectorComponent);
constructor() {
afterNextRender(() =>
this.source().instance.on('featuresloadend', function (evt: VectorSourceEvent) {
evt.features?.forEach((f) => {
f.set('magnitude', parseMagnitudeFromName(f.get('name')), true);
});
})
);
}
} 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.
earthquake-custom-symbol.react.tsximport { useEffect, useState } from 'react';
import { getBottomLeft, getTopRight } from 'ol/extent';
import type { FeatureLike } from 'ol/Feature';
import KML from 'ol/format/KML';
import Polygon from 'ol/geom/Polygon';
import { DEVICE_PIXEL_RATIO } from 'ol/has';
import { toContext } from 'ol/render';
import type OLVectorSource from 'ol/source/Vector';
import type { VectorSourceEvent } from 'ol/source/Vector';
import Fill from 'ol/style/Fill';
import Icon from 'ol/style/Icon';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
ImageTileSource,
Map,
TileLayer,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
const getSymbolOutline = (function () {
const path = [
[0, 0],
[4, 2],
[6, 0],
[10, 5],
[6, 3],
[4, 5],
[0, 0],
];
const symbolOutline = new Polygon([path]);
symbolOutline.rotate(1.2, path[0]);
return function (scale: number, offset: number) {
const outline = symbolOutline.clone();
outline.scale(scale, scale, path[0]);
const origin = getBottomLeft(outline.getExtent());
outline.translate(offset - origin[0], offset - origin[1]);
return outline;
};
})();
const styleCache: Record<number, Style> = {};
const style = function (feature: FeatureLike): Style {
const magnitude: number = feature.get('magnitude');
let style = styleCache[magnitude];
if (!style) {
// Sized for the events' density: most of them are 2 to 3 and lie within some 50 km.
const scale = 1 + (magnitude - 2);
const lineWidth = 2;
const outline = getSymbolOutline(scale, Math.ceil(lineWidth / 2));
const canvas = document.createElement('canvas');
const vectorContext = toContext(canvas.getContext('2d') as CanvasRenderingContext2D, {
size: getTopRight(outline.getExtent()).map((n) => Math.ceil(n + lineWidth / 2)),
pixelRatio: DEVICE_PIXEL_RATIO,
});
vectorContext.setStyle(
new Style({
fill: new Fill({ color: 'rgba(255, 153, 0, 0.4)' }),
stroke: new Stroke({
color: 'rgba(255, 204, 0, 0.2)',
width: 2,
}),
})
);
vectorContext.drawGeometry(outline);
style = new Style({
image: new Icon({
img: canvas,
scale: 1 / DEVICE_PIXEL_RATIO,
}),
});
styleCache[magnitude] = style;
}
return style;
};
// tremors.kml names each event by its magnitude, "M 3.4 - 1995 Mar 7".
function parseMagnitudeFromName(name: string): number {
return parseFloat(name.slice(2));
}
const format = new KML({
extractStyles: false,
});
/**
* The seismic events around Kraków since 1978 read from a KML file, each drawn as a lightning-shaped symbol sized by
* its magnitude: the symbol is drawn once per magnitude onto a canvas with the immediate rendering API and used as the
* image of an icon.
*/
export function EarthquakeCustomSymbol() {
// The source is made after the first commit, so the state carries it to the effect.
const [source, setSource] = useState<OLVectorSource | null>(null);
useEffect(() => {
const onLoadEnd = (evt: VectorSourceEvent) => {
evt.features?.forEach((f) => {
f.set('magnitude', parseMagnitudeFromName(f.get('name')), true);
});
};
source?.on('featuresloadend', onLoadEnd);
return () => source?.un('featuresloadend', onLoadEnd);
}, [source]);
return (
<Map height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={9}>
<Coordinate x={19.25} y={50.15} srid="EPSG:4326" />
</View>
<TileLayer>
<ImageTileSource
url="https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
maxZoom={16}
attributions="Tiles © Esri — Esri, HERE, Garmin, © OpenStreetMap contributors, and the GIS user community"
/>
</TileLayer>
<VectorLayer style={style}>
<VectorSource
ref={setSource}
url="assets/krakow/tremors.kml"
format={format}
attributions="Seismic events: U.S. Geological Survey"
/>
</VectorLayer>
<TileLayer>
<ImageTileSource
url="https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer/tile/{z}/{y}/{x}"
maxZoom={16}
/>
</TileLayer>
</Map>
);
}How the React version works
Seismic events around Kraków since 1978 from a KML file, each a lightning-shaped symbol sized by its magnitude: the symbol is drawn once per magnitude onto a canvas with the immediate rendering API and used as the image of an icon.
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. The symbols are cached by magnitude in the module in both versions.
From Angular to React
| Angular | React |
|---|---|
<aol-source-imagetile> for the base map and its labels | <ImageTileSource> in two <TileLayer>s |
afterNextRender and viewChild of the source | ref={setSource} into useState and a useEffect keyed on the source: the adapter makes the source after the first commit, so a plain ref is still empty in the first effect |
the featuresloadend listener added after render | source.on('featuresloadend', …) in the effect, removed with un in its cleanup |
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. The effect adds the featuresloadend listener to the source and removes it in its cleanup, so a StrictMode double run leaves one listener.
Architecture and OpenLayers mechanics
On featuresloadend, each KML event (extractStyles: false) parses its magnitude silently onto the feature. The first time the style function encounters a given magnitude value, it scales the lightning-bolt polygon coordinates, renders them sharply onto an off-screen canvas via toContext with pixelRatio: DEVICE_PIXEL_RATIO, wraps that canvas in an Icon with scale: 1 / DEVICE_PIXEL_RATIO, and stores the Style in styleCache—sharing just 28 cached styles across all 1,130 tremors.
How it works
featuresloadendextracts each tremor’s magnitude silently onto the feature without firing 1,130 change events.toContextrasterises a scaled lightning-bolt polygon onto an off-screen canvas the first time each magnitude value is encountered.- Pairing
pixelRatio: DEVICE_PIXEL_RATIOontoContextwithscale: 1 / DEVICE_PIXEL_RATIOon the Icon keeps cached symbols razor-sharp on Retina screens. styleCachereuses just 28 pre-rendered icon styles across all 1,130 seismic features while a reference label layer sits on top.
Pitfalls
- Rendering off-screen icon canvases at 1x pixel ratio without
DEVICE_PIXEL_RATIOcompensation produces visibly blurry glyphs on modern 2x/3x laptops and phones. - Keep
extractStyles: falseon the KML source so unstyled KML placemarks do not fall back to Google Earth yellow pushpins.
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.