Layers · Angular, React and OpenLayers
Group layers and set them together
Organize OpenLayers layers into a hierarchical LayerGroup tree and control combined visibility and multiplied opacity in Angular and React.

What this example shows
Over an OpenStreetMap backdrop of Kraków, an aol-layer-group bundles GUGiK’s aerial orthophotomap together with municipal boundary lines. Beneath the map, an interactive hierarchical layer tree lets you toggle visibility checkboxes and scrub opacity sliders independently for the base street map, for the group as a whole, and for each individual child layer inside the group.
When you need it
Enterprise geoportals group dozens of related services into thematic folders—such as Cadastre, Utilities, Environmental Protection or Planning—so users can hide or fade an entire theme with one click without losing individual sub-layer adjustments.
Using OpenLayers’ native LayerGroup keeps folder hierarchy inside the map model itself rather than writing manual loops that overwrite child layer states.
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.
layer-group.tsimport { NgTemplateOutlet } from '@angular/common';
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerGroupComponent,
LayerTileComponent,
MapComponent,
SourceOsmComponent,
SourceTileWMSComponent,
SourceTileWMTSComponent,
TileGridWMTSComponent,
ViewComponent,
} from 'cc-openlayers';
import { getTopLeft, getWidth } from 'ol/extent';
import { EXTENT } from 'ol/proj/epsg3857';
const size = getWidth(EXTENT) / 256;
/** The visibility and opacity of one layer, set from the layer tree. */
function layerState() {
return { visible: signal(true), opacity: signal(1) };
}
/** OpenStreetMap and a group of the national orthophoto and municipal boundaries, each with visibility and opacity set from a layer tree. */
@Component({
selector: 'app-layer-group',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerGroupComponent,
LayerTileComponent,
MapComponent,
NgTemplateOutlet,
SourceOsmComponent,
SourceTileWMSComponent,
SourceTileWMTSComponent,
TileGridWMTSComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px">
<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 [visible]="osm.visible()" [opacity]="osm.opacity()"><aol-source-osm /></aol-layer-tile>
<aol-layer-group [visible]="group.visible()" [opacity]="group.opacity()">
<aol-layer-tile [visible]="orthophoto.visible()" [opacity]="orthophoto.opacity()">
<aol-source-tilewmts
attributions='Tiles © <a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>'
url="https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution"
layer="ORTOFOTOMAPA"
matrixSet="EPSG:3857"
format="image/jpeg"
projection="EPSG:3857"
[style]="'default'"
[wrapX]="true"
>
<aol-tilegrid-wmts [origin]="origin" [resolutions]="resolutions" [matrixIds]="matrixIds" />
</aol-source-tilewmts>
</aol-layer-tile>
<aol-layer-tile [visible]="boundaries.visible()" [opacity]="boundaries.opacity()">
<aol-source-tilewms
url="https://mapy.geoportal.gov.pl/wss/service/PZGIK/PRG/WMS/AdministrativeBoundaries"
[params]="{ LAYERS: 'A03_Granice_gmin', TILED: true }"
crossOrigin="anonymous"
/>
</aol-layer-tile>
</aol-layer-group>
</aol-map>
<div class="example-controls">
<p class="example-hint">Open a layer node to change its properties.</p>
<ul>
<li>
<details>
<summary>OSM layer</summary>
<ng-container *ngTemplateOutlet="properties; context: { $implicit: osm }" />
</details>
</li>
<li>
<details>
<summary>Layer group</summary>
<ng-container *ngTemplateOutlet="properties; context: { $implicit: group }" />
</details>
<ul>
<li>
<details>
<summary>Orthophoto layer</summary>
<ng-container *ngTemplateOutlet="properties; context: { $implicit: orthophoto }" />
</details>
</li>
<li>
<details>
<summary>Municipal boundaries layer</summary>
<ng-container *ngTemplateOutlet="properties; context: { $implicit: boundaries }" />
</details>
</li>
</ul>
</li>
</ul>
</div>
<ng-template #properties let-layer>
<fieldset>
<label>
visible
<input type="checkbox" [checked]="layer.visible()" (change)="layer.visible.set(checked($event))" />
</label>
<label>
opacity
<input
type="range"
min="0"
max="1"
step="0.01"
[value]="layer.opacity()"
(input)="layer.opacity.set(number($event))"
/>
</label>
</fieldset>
</ng-template>
`,
})
export class LayerGroup {
readonly osm = layerState();
readonly group = layerState();
readonly orthophoto = layerState();
readonly boundaries = layerState();
protected readonly origin = getTopLeft(EXTENT);
protected readonly resolutions = Array.from({ length: 20 }, (_, z) => size / 2 ** z);
protected readonly matrixIds = Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`);
protected checked(event: Event): boolean {
return (event.target as HTMLInputElement).checked;
}
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.
layer-group.react.tsximport { useState, type ChangeEvent } from 'react';
import { getTopLeft, getWidth } from 'ol/extent';
import { EXTENT } from 'ol/proj/epsg3857';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
LayerGroup as LayerGroupDeclaration,
Map,
OSMSource,
TileLayer,
TileWMSSource,
View,
WMTSSource,
useWMTSTileGrid,
} from 'cc-openlayers/react';
const size = getWidth(EXTENT) / 256;
const origin = getTopLeft(EXTENT);
const resolutions = Array.from({ length: 20 }, (_, z) => size / 2 ** z);
const matrixIds = Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`);
const boundariesParams = { LAYERS: 'A03_Granice_gmin', TILED: true };
/** The visibility and opacity of one layer, set from the layer tree. */
function useLayerState() {
const [visible, setVisible] = useState(true);
const [opacity, setOpacity] = useState(1);
return { visible, setVisible, opacity, setOpacity };
}
type LayerState = ReturnType<typeof useLayerState>;
function checked(event: ChangeEvent<HTMLInputElement>): boolean {
return event.target.checked;
}
function number(event: ChangeEvent<HTMLInputElement>): number {
return event.target.valueAsNumber;
}
function Properties({ layer }: { layer: LayerState }) {
return (
<fieldset>
<label>
visible
<input type="checkbox" checked={layer.visible} onChange={(event) => layer.setVisible(checked(event))} />
</label>
<label>
opacity
<input
type="range"
min="0"
max="1"
step="0.01"
value={layer.opacity}
onChange={(event) => layer.setOpacity(number(event))}
/>
</label>
</fieldset>
);
}
/** OpenStreetMap and a group of the national orthophoto and municipal boundaries, each with visibility and opacity set from a layer tree. */
export function LayerGroup() {
const osm = useLayerState();
const group = useLayerState();
const orthophoto = useLayerState();
const boundaries = useLayerState();
const tileGrid = useWMTSTileGrid({ origin, resolutions, matrixIds });
return (
<>
<Map height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={11}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer visible={osm.visible} opacity={osm.opacity}>
<OSMSource />
</TileLayer>
<LayerGroupDeclaration visible={group.visible} opacity={group.opacity}>
<TileLayer visible={orthophoto.visible} opacity={orthophoto.opacity}>
<WMTSSource
attributions='Tiles © <a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>'
url="https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution"
layer="ORTOFOTOMAPA"
matrixSet="EPSG:3857"
format="image/jpeg"
projection="EPSG:3857"
style="default"
wrapX={true}
tileGrid={tileGrid}
/>
</TileLayer>
<TileLayer visible={boundaries.visible} opacity={boundaries.opacity}>
<TileWMSSource
url="https://mapy.geoportal.gov.pl/wss/service/PZGIK/PRG/WMS/AdministrativeBoundaries"
params={boundariesParams}
crossOrigin="anonymous"
/>
</TileLayer>
</LayerGroupDeclaration>
</Map>
<div className="example-controls">
<p className="example-hint">Open a layer node to change its properties.</p>
<ul>
<li>
<details>
<summary>OSM layer</summary>
<Properties layer={osm} />
</details>
</li>
<li>
<details>
<summary>Layer group</summary>
<Properties layer={group} />
</details>
<ul>
<li>
<details>
<summary>Orthophoto layer</summary>
<Properties layer={orthophoto} />
</details>
</li>
<li>
<details>
<summary>Municipal boundaries layer</summary>
<Properties layer={boundaries} />
</details>
</li>
</ul>
</li>
</ul>
</div>
</>
);
}How the React version works
OpenStreetMap and a group of the orthophoto and the municipal borders each have a “visible” box and an “opacity” slider. Hiding the group hides both its layers although their own boxes stay checked, and the opacity of the group multiplies with that of its layers.
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 compute the WMTS tile grid of GUGiK's orthophoto (origin, 20 resolutions, ids EPSG:3857:z) in the same way; in React the useWMTSTileGrid hook creates it once from module constants. GUGiK's WMS serves the municipal borders with the same parameters.
From Angular to React
| Angular | React |
|---|---|
<aol-layer-group> with the layers inside | <LayerGroup> with the layers inside (imported as LayerGroupDeclaration, because the name belongs to the example) |
an object with two signal calls per tree node | a useLayerState() hook with two useState calls |
| a repeated template fragment with the fields | a small Properties component |
<aol-source-tilewmts> with <aol-tilegrid-wmts> inside | <WMTSSource tileGrid={tileGrid}> with useWMTSTileGrid(...) |
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. LayerGroup is the layers' parent in context: the layers go into the group's collection, not the map's.
Architecture and OpenLayers mechanics
Mounting aol-layer-group after the OpenStreetMap layer stacks all of its child layers above the street map. During rendering, OpenLayers flattens the hierarchy and computes effective state per leaf layer: a child renders only when both the group and the child have [visible] true, its effective alpha is the product of group [opacity] and child [opacity] (for example 0.5 * 0.5 = 0.25), and effective extent/zoom ranges intersect both parent and child constraints.
In the UI below the map, a single reusable ng-template renders visibility and opacity controls uniformly for standalone layers, the parent group and nested children.
How it works
aol-layer-groupcombines the GUGiK orthophotomap and municipal boundaries into a single thematic folder drawn above OpenStreetMap.- Independent signals back
[visible]and[opacity]on the street map, the group and each child layer, rendered through a shared treeng-template. - OpenLayers multiplies group and child opacities at render time (0.5 * 0.5 = 0.25) and intersects their visibility, extent and zoom limits.
- Hiding a parent group suppresses all of its children immediately while preserving each child’s own visibility and opacity settings for when the group is turned back on.
Pitfalls
- Group opacity multiplies onto each child draw call individually rather than compositing the group onto an off-screen buffer first—meaning at 0.5 group opacity, the orthophotomap shows faintly through the boundary strokes drawn above it.
- Z-index sorting in OpenLayers is global across the flattened render list rather than scoped strictly inside a group; a group’s Z-index merely acts as the fallback default for children that leave their own Z-index unset.
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.