Tile and image services · Angular, React and OpenLayers

A WMS layer's legend for the view's scale

Fetch a scale-aware WMS GetLegendGraphic image in OpenLayers with getLegendUrl and refresh it automatically whenever view resolution changes.

Poland's voivodeships at zoom 6 with their boundaries in pink over OpenStreetMap, and below the map the service's legend, a pink line for Granice województw.
A screenshot of the example. Voivodeships: Państwowy Rejestr Granic © GUGiK. Map data © OpenStreetMap contributors.

What this example shows

Over southern and central Poland at zoom 6, voivodeship boundaries from GUGiK’s national WMS appear in pink above OpenStreetMap while an external legend graphic rendered directly by the WMS server sits cleanly below the viewport.

Zooming in or out recalculates the map’s denominator scale and updates the legend image URL automatically so scale-dependent server symbology stays synchronized with the map.

When you need it

Complex planning, geological and cadastral WMS layers use server-side SLD/MapServer rules whose colours, stroke weights and active symbol classes change across zoom scales.

Requesting legends dynamically from the WMS server via GetLegendGraphic guarantees the UI key always matches actual server cartography without maintaining duplicate symbol icons in frontend assets.

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.

wms-getlegendgraphic.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerImageComponent,
  LayerTileComponent,
  MapComponent,
  SourceImageWMSComponent,
  SourceOsmComponent,
  ViewComponent,
} from 'cc-openlayers';
import type { ObjectEvent } from 'ol/Object';
import type View from 'ol/View';

/** Voivodeship boundaries from a WMS with the legend of the layer, requested again whenever the resolution changes. */
@Component({
  selector: 'app-wms-getlegendgraphic',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerImageComponent,
    LayerTileComponent,
    MapComponent,
    SourceImageWMSComponent,
    SourceOsmComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="6" (changeResolution)="updateLegend($event)">
        <aol-coordinate [x]="19.4" [y]="52.1" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
      <aol-layer-image [extent]="extent">
        <aol-source-imagewms
          url="https://mapy.geoportal.gov.pl/wss/service/PZGIK/PRG/WMS/AdministrativeBoundaries"
          [params]="{ LAYERS: 'A01_Granice_wojewodztw' }"
          [ratio]="1"
          serverType="mapserver"
          attributions="Administrative boundaries © GUGiK"
        />
      </aol-layer-image>
    </aol-map>
    <div class="example-controls">
      <span>Legend:</span>
      <img [src]="legendUrl()" alt="Legend of the boundaries layer" />
    </div>
  `,
})
export class WmsGetlegendgraphic implements AfterViewInit {
  readonly legendUrl = signal('');

  /** Poland in Web Mercator. */
  protected readonly extent = [1525077, 6207260, 2771855, 7381298];
  private readonly source = viewChild.required(SourceImageWMSComponent);
  private readonly view = viewChild.required(ViewComponent);

  ngAfterViewInit(): void {
    this.legendUrl.set(this.legendFor(this.view().instance));
  }

  protected updateLegend(event: ObjectEvent): void {
    this.legendUrl.set(this.legendFor(event.target as View));
  }

  /** The service asks for the SLD version of a legend request. */
  private legendFor(view: View): string {
    return this.source().instance.getLegendUrl(view.getResolution(), { SLD_VERSION: '1.1.0' }) ?? '';
  }
}

Architecture and OpenLayers mechanics

The image WMS source exposes getLegendUrl, which constructs a standard OGC GetLegendGraphic query incorporating the active view resolution so the server knows which scale rules apply. Initial legend resolution runs in ngAfterViewInit once both view and source instances exist, and (changeResolution) on the view refreshes the URL on every zoom change.

Because GUGiK’s MapServer implementation under WMS 1.3.0 requires an explicit Styled Layer Descriptor version that OpenLayers omits by default, passing SLD_VERSION: '1.1.0' ensures a valid PNG graphic is returned.

How it works

  • getLegendUrl on the image WMS source builds a scale-aware GetLegendGraphic URL from the current view resolution.
  • (changeResolution) refreshes the legend image URL whenever the user zooms in or out.
  • ngAfterViewInit computes the initial legend URL as soon as the view and WMS source are initialised.
  • Passing SLD_VERSION: '1.1.0' satisfies MapServer’s strict WMS 1.3.0 GetLegendGraphic requirement.

Pitfalls

  • Omitting the SLD version parameter against strict MapServer WMS 1.3.0 endpoints returns an OGC XML exception document instead of an image, showing a broken-image icon in the browser.
  • getLegendUrl forwards LAYERS directly when configured as a single layer name string; if a source configures multiple layers or an array, pass an explicit single LAYER name parameter when building each legend URL.

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.