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.

A light grey map west of Kraków with orange lightning symbols of seismic events, densest over the coal basin of Upper Silesia between Katowice, Rybnik and Karviná.
A screenshot of the example. Seismic events: U.S. Geological Survey. Base map: Esri World Light Gray (Esri, HERE, Garmin, OpenStreetMap contributors and the GIS user community).

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

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

  • featuresloadend extracts each tremor’s magnitude silently onto the feature without firing 1,130 change events.
  • toContext rasterises a scaled lightning-bolt polygon onto an off-screen canvas the first time each magnitude value is encountered.
  • Pairing pixelRatio: DEVICE_PIXEL_RATIO on toContext with scale: 1 / DEVICE_PIXEL_RATIO on the Icon keeps cached symbols razor-sharp on Retina screens.
  • styleCache reuses 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_RATIO compensation produces visibly blurry glyphs on modern 2x/3x laptops and phones.
  • Keep extractStyles: false on the KML source so unstyled KML placemarks do not fall back to Google Earth yellow pushpins.

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.