Layers · Angular, React and OpenLayers
Order layers by Z-index
Control OpenLayers vector and raster stacking order dynamically with zIndex bindings while keeping an unmanaged setMap overlay pinned on top.

What this example shows
Zoomed closely onto Kraków’s Main Square at zoom 18, three geometric vector markers overlap above an OpenStreetMap backdrop: a blue square, a red triangle and a green star. Two numeric inputs below the map let you edit the Z-index of the square and triangle; each committed value changes which shape draws on top—while the green star remains permanently above both regardless of how high you set their numbers.
When you need it
In dynamic GIS workspaces where users enable thematic layers in arbitrary order, point markers and labels must still render reliably above polygons, and polygons above raster backdrops.
Explicit Z-indices decouple visual stacking from layer insertion order, while unmanaged layers provide a dedicated top-most plane for temporary measurement sketches, selection highlights or crosshairs that must never be buried.
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-z-index.tsimport {
ChangeDetectionStrategy,
Component,
DestroyRef,
afterNextRender,
inject,
signal,
viewChild,
} from '@angular/core';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import type { FlatStyle } from 'ol/style/flat';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
FeatureComponent,
GeometryPointComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceOsmComponent,
SourceVectorComponent,
ViewComponent,
} from 'cc-openlayers';
const centre = [2219354, 6456916];
const styles: Record<'square' | 'triangle' | 'star', FlatStyle> = {
square: {
'shape-points': 4,
'shape-radius': 80,
'shape-angle': Math.PI / 4,
'shape-stroke-color': '#000000',
'shape-stroke-width': 1,
'shape-fill-color': '#0000ff',
},
triangle: {
'shape-points': 3,
'shape-radius': 80,
'shape-rotation': Math.PI / 4,
'shape-stroke-color': '#000000',
'shape-stroke-width': 1,
'shape-fill-color': '#ff0000',
},
star: {
'shape-points': 5,
'shape-radius': 80,
'shape-radius2': 40,
'shape-rotation': Math.PI / 4,
'shape-stroke-color': '#000000',
'shape-stroke-width': 1,
'shape-fill-color': '#008000',
},
};
/** Two managed layers over a street map, ordered by Z-index inputs, and one unmanaged layer that stays on top. */
@Component({
selector: 'app-layer-z-index',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
FeatureComponent,
GeometryPointComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceOsmComponent,
SourceVectorComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="18"><aol-coordinate [x]="centre[0]" [y]="centre[1]" /></aol-view>
<aol-layer-tile><aol-source-osm /></aol-layer-tile>
<aol-layer-vector [style]="styles.square" [zIndex]="squareIndex()">
<aol-source-vector>
<aol-feature>
<aol-geometry-point><aol-coordinate [x]="centre[0]" [y]="centre[1]" /></aol-geometry-point>
</aol-feature>
</aol-source-vector>
</aol-layer-vector>
<aol-layer-vector [style]="styles.triangle" [zIndex]="triangleIndex()">
<aol-source-vector>
<aol-feature>
<aol-geometry-point><aol-coordinate [x]="centre[0]" [y]="centre[1] + 40" /></aol-geometry-point>
</aol-feature>
</aol-source-vector>
</aol-layer-vector>
</aol-map>
<div class="example-controls">
<p class="example-hint">
The street map has no Z-index, which counts as 0, and layers of the same index keep their order: a negative
index puts a shape below the street map.
</p>
<label>
<input type="number" [value]="squareIndex()" (change)="squareIndex.set(zIndex($event))" />
Square layer Z-index
</label>
<label>
<input type="number" [value]="triangleIndex()" (change)="triangleIndex.set(zIndex($event))" />
Triangle layer Z-index
</label>
</div>
`,
})
export class LayerZIndex {
readonly squareIndex = signal(1);
readonly triangleIndex = signal(0);
/** The star layer belongs to no map's layer list: it renders above all managed layers, whatever their Z-index. */
readonly star = new VectorLayer({
source: new VectorSource({ features: [new Feature(new Point([centre[0] + 40, centre[1] + 40]))] }),
style: styles.star,
});
protected readonly centre = centre;
protected readonly styles = styles;
private readonly map = viewChild.required(MapComponent);
constructor() {
afterNextRender(() => this.star.setMap(this.map().instance));
inject(DestroyRef).onDestroy(() => this.star.setMap(null));
}
protected zIndex(event: Event): number {
return parseInt((event.target as HTMLInputElement).value, 10) || 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.
layer-z-index.react.tsximport { useEffect, useState, type ChangeEvent } from 'react';
import Feature from 'ol/Feature.js';
import Point from 'ol/geom/Point.js';
import VectorLayer from 'ol/layer/Vector.js';
import type OLMap from 'ol/Map.js';
import VectorSource from 'ol/source/Vector.js';
import type { FlatStyle } from 'ol/style/flat.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
Feature as FeatureDeclaration,
Map,
OSMSource,
PointGeometry,
TileLayer,
VectorLayer as VectorLayerDeclaration,
VectorSource as VectorSourceDeclaration,
View,
} from 'cc-openlayers/react';
const centre = [2219354, 6456916];
const styles: Record<'square' | 'triangle' | 'star', FlatStyle> = {
square: {
'shape-points': 4,
'shape-radius': 80,
'shape-angle': Math.PI / 4,
'shape-stroke-color': '#000000',
'shape-stroke-width': 1,
'shape-fill-color': '#0000ff',
},
triangle: {
'shape-points': 3,
'shape-radius': 80,
'shape-rotation': Math.PI / 4,
'shape-stroke-color': '#000000',
'shape-stroke-width': 1,
'shape-fill-color': '#ff0000',
},
star: {
'shape-points': 5,
'shape-radius': 80,
'shape-radius2': 40,
'shape-rotation': Math.PI / 4,
'shape-stroke-color': '#000000',
'shape-stroke-width': 1,
'shape-fill-color': '#008000',
},
};
function zIndex(event: ChangeEvent<HTMLInputElement>): number {
return parseInt(event.target.value, 10) || 0;
}
/** Two managed layers over a street map, ordered by Z-index inputs, and one unmanaged layer that stays on top. */
export function LayerZIndex() {
const [squareIndex, setSquareIndex] = useState(1);
const [triangleIndex, setTriangleIndex] = useState(0);
const [map, setMap] = useState<OLMap | null>(null);
/** The star layer belongs to no map's layer list: it renders above all managed layers, whatever their Z-index. */
const [star] = useState(
() =>
new VectorLayer({
source: new VectorSource({ features: [new Feature(new Point([centre[0] + 40, centre[1] + 40]))] }),
style: styles.star,
})
);
useEffect(() => {
if (!map) return;
star.setMap(map);
return () => star.setMap(null);
}, [map, star]);
return (
<>
<Map ref={setMap} height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={18}>
<Coordinate x={centre[0]} y={centre[1]} />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
<VectorLayerDeclaration style={styles.square} zIndex={squareIndex}>
<VectorSourceDeclaration>
<FeatureDeclaration>
<PointGeometry>
<Coordinate x={centre[0]} y={centre[1]} />
</PointGeometry>
</FeatureDeclaration>
</VectorSourceDeclaration>
</VectorLayerDeclaration>
<VectorLayerDeclaration style={styles.triangle} zIndex={triangleIndex}>
<VectorSourceDeclaration>
<FeatureDeclaration>
<PointGeometry>
<Coordinate x={centre[0]} y={centre[1] + 40} />
</PointGeometry>
</FeatureDeclaration>
</VectorSourceDeclaration>
</VectorLayerDeclaration>
</Map>
<div className="example-controls">
<p className="example-hint">
The street map has no Z-index, which counts as 0, and layers of the same index keep their order: a negative
index puts a shape below the street map.
</p>
<label>
<input type="number" defaultValue={squareIndex} onChange={(event) => setSquareIndex(zIndex(event))} />
Square layer Z-index
</label>
<label>
<input type="number" defaultValue={triangleIndex} onChange={(event) => setTriangleIndex(zIndex(event))} />
Triangle layer Z-index
</label>
</div>
</>
);
}How the React version works
Two number fields set the z-index of the square and the triangle layers above the street map, whose z-index is 0. The star lies on an unmanaged layer (layer.setMap(map)), so it is always on top, whatever the z-indexes.
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 flat styles of the three shapes are the same in both versions.
From Angular to React
| Angular | React |
|---|---|
(change) on the number field | onChange on an uncontrolled field (defaultValue): React reports every change of the value, so the z-index changes while typing |
[zIndex]="squareIndex()" | zIndex={squareIndex} |
the class field star and afterNextRender(() => star.setMap(map)) with cleanup in DestroyRef | useState with an initialiser for the star's layer and a useEffect that calls setMap(map) and setMap(null) in its cleanup |
viewChild.required(MapComponent) | ref={setMap}: the map in state, so the star's effect runs once the map exists |
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 star's layer does not belong to the adapter, so the example's effect attaches it to the map and detaches it on unmount.
Architecture and OpenLayers mechanics
Before painting each frame, OpenLayers sorts managed layers by their numeric [zIndex], breaking ties by template/collection order and treating omitted Z-indices (such as the base street map) as 0. Starting the square at 1 and the triangle at 0 draws the square over both the street map and the triangle until you raise the triangle’s number.
The green star’s layer is intentionally excluded from the map’s layer collection and attached imperatively via setMap inside afterNextRender. OpenLayers treats unmanaged layers without an explicit Z-index as having infinite stacking priority—drawing them above every managed layer—and DestroyRef detaches it cleanly via setMap(null) on teardown.
How it works
- OpenLayers sorts managed layers by Z-index on every frame, defaulting unset layers (including the base street map) to 0 and preserving collection order on ties.
- Two numeric inputs bind directly to
[zIndex]on the square and triangle vector layers so committing a new number reorders them immediately. - Attaching the star’s layer with
setMapturns it into an unmanaged overlay whose unset Z-index evaluates as infinity, keeping it above all managed layers. afterNextRenderattaches the unmanaged layer once the map instance exists, andDestroyRefcleans it up withsetMap(null)on component destroy.
Pitfalls
- Assigning a negative Z-index (such as -1) pushes your vector layer underneath a base map whose default Z-index is 0, making your features disappear behind opaque street tiles.
- Unmanaged layers attached via
setMapdo not appear in map.getLayers(), which keeps temporary UI gizmos out of user-facing layer switchers automatically. - Never pass a layer already present in the map’s layer collection to
setMap—OpenLayers throws a duplicate-layer error if the same instance is registered twice.
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.