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.

The Main Square in Kraków on a street map at zoom 18, with a blue square over a red triangle and a green star over both.
A screenshot of the example. Map data © OpenStreetMap contributors.

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

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 setMap turns it into an unmanaged overlay whose unset Z-index evaluates as infinity, keeping it above all managed layers.
  • afterNextRender attaches the unmanaged layer once the map instance exists, and DestroyRef cleans it up with setMap(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 setMap do 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.

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.