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.

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.tsimport { 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' }) ?? '';
}
} 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.
wms-getlegendgraphic.react.tsximport { useCallback, useState } from 'react';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
ImageLayer,
ImageWMSSource,
Map,
OSMSource,
TileLayer,
View,
} from 'cc-openlayers/react';
import type { ObjectEvent } from 'ol/Object.js';
import type OLView from 'ol/View.js';
import type ImageWMS from 'ol/source/ImageWMS.js';
/** Poland in Web Mercator. */
const extent = [1525077, 6207260, 2771855, 7381298];
const params = { LAYERS: 'A01_Granice_wojewodztw' };
/** The service asks for the SLD version of a legend request. */
function legendFor(source: ImageWMS, resolution: number | undefined): string {
return source.getLegendUrl(resolution, { SLD_VERSION: '1.1.0' }) ?? '';
}
/** Voivodeship boundaries from a WMS with the legend of the layer, requested again whenever the resolution changes. */
export function WmsGetlegendgraphic() {
// State, not refs: the legend is asked for once the map has made the source and the view.
const [source, setSource] = useState<ImageWMS | null>(null);
const [view, setView] = useState<OLView | null>(null);
const [resolution, setResolution] = useState<number | undefined>(undefined);
const legendUrl = source && view ? legendFor(source, resolution) : '';
const takeView = useCallback((live: OLView | null) => {
setView(live);
setResolution(live?.getResolution());
}, []);
const updateLegend = (event: ObjectEvent) => setResolution((event.target as OLView).getResolution());
return (
<>
<Map height="480px">
<DefaultInteractions />
<DefaultControls />
<View ref={takeView} zoom={6} onChangeResolution={updateLegend}>
<Coordinate x={19.4} y={52.1} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
<ImageLayer extent={extent}>
<ImageWMSSource
ref={setSource}
url="https://mapy.geoportal.gov.pl/wss/service/PZGIK/PRG/WMS/AdministrativeBoundaries"
params={params}
ratio={1}
serverType="mapserver"
attributions="Administrative boundaries © GUGiK"
/>
</ImageLayer>
</Map>
<div className="example-controls">
<span>Legend:</span>
<img src={legendUrl} alt="Legend of the boundaries layer" />
</div>
</>
);
}How the React version works
Below the map, the legend of the border layer from GetLegendGraphic, fetched again at each change of resolution.
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.
From Angular to React
| Angular | React |
|---|---|
(changeResolution) on aol-view | onChangeResolution on View |
viewChild of the source and the view | ref={setSource} and ref={takeView}: both in state, because the legend depends on them while rendering |
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
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
getLegendUrlon 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.ngAfterViewInitcomputes 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.
getLegendUrlforwardsLAYERSdirectly 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.
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.