Essentials · Angular, React and OpenLayers

Map state in the URL with the link interaction

Persist OpenLayers map center, zoom, rotation, layer visibility and custom query parameters in the browser URL using the Link interaction.

A street map of central Kraków with a checkbox below it that writes the example parameter into the address.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Panning, zooming or rotating the street map of central Kraków updates the browser’s address bar query parameters (x, y, z, r and l) automatically, while a checkbox beneath the map toggles an application-owned example query parameter in that same URL.

Reloading the tab, sharing the link or clicking the browser’s Back and Forward buttons restores both the exact camera state and the custom checkbox state in lockstep.

When you need it

Every collaborative WebGIS tool benefits from shareable deep links: pasting the current URL into a chat or ticket should reopen the exact parcel, zoom scale, layer visibility and UI filter state the sender saw.

OpenLayers’ built-in Link interaction handles map-camera URL encoding and restoration out of the box while exposing hooks so application-specific query parameters live peacefully alongside map coordinates.

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.

link.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  LinkInteractionComponent,
  MapComponent,
  SourceOsmComponent,
  ViewComponent,
} from 'cc-openlayers';

/** The view and a checkbox kept in the page address by the link interaction, so a reload or a shared link restores them. */
@Component({
  selector: 'app-link',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    LinkInteractionComponent,
    MapComponent,
    SourceOsmComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { '(window:popstate)': 'followRemoval()' },
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-interaction-link />
      <aol-control-defaults />
      <aol-view [zoom]="13">
        <aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
    </aol-map>
    <div class="example-controls">
      <label>
        <input type="checkbox" [checked]="checked()" (change)="toggle($event)" />
        See the <code>example</code> search parameter update when toggling this checkbox.
      </label>
      <p class="example-hint">Move the map: the address keeps its centre, zoom and rotation.</p>
    </div>
  `,
})
export class Link implements AfterViewInit {
  readonly checked = signal(false);
  private readonly link = viewChild.required(LinkInteractionComponent);

  /** Reads the parameter from the address and follows its changes (back and forward in the history). */
  ngAfterViewInit(): void {
    const initial = this.link().instance.track('example', (value) => this.checked.set(value === 'checked'));
    this.checked.set(initial === 'checked');
  }

  /**
   * Unchecks the box when the back and forward buttons return to an address without the parameter: since OpenLayers
   * 10.11, `track` calls back only when the parameter has a value.
   */
  protected followRemoval(): void {
    if (!new URL(window.location.href).searchParams.has('example')) this.checked.set(false);
  }

  /** Writes the parameter into the address; null removes it. */
  protected toggle(event: Event): void {
    const checked = (event.target as HTMLInputElement).checked;
    this.checked.set(checked);
    this.link().instance.update('example', checked ? 'checked' : null);
  }
}

Architecture and OpenLayers mechanics

Mounting aol-interaction-link synchronises view centre, zoom, rotation and layer visibility with URL search parameters on every settled move and hydrates them on initial page load. Custom application state hooks into the same lifecycle via track (reading the initial example parameter after ngAfterViewInit and listening for history updates) and update (setting a string value or passing null to delete the parameter).

To account for OpenLayers 10.11+ behaviour where track does not fire when a tracked key disappears completely on browser Back navigation, a lightweight followRemoval() handler on (window:popstate) keeps UI state accurate when returning to parameter-free URLs.

How it works

  • aol-interaction-link persists camera centre, zoom, rotation and layer visibility in URL query parameters and restores them on page load.
  • track reads the initial example parameter and notifies the component when browser Back/Forward navigation changes its value.
  • update writes new parameter values into the address bar, while passing null removes the key cleanly.
  • Initial parameter hydration runs in ngAfterViewInit once the underlying OpenLayers interaction instance is ready.

Pitfalls

  • Since OpenLayers 10.11, track stops invoking its callback when Back navigation removes a parameter entirely from the URL; listening to (window:popstate) with followRemoval() prevents stale checked states.
  • Two maps with active Link interactions on the same page will overwrite each other’s query keys unless each configures a distinct parameter prefix.
  • By default each settled pan pushes a new browser history entry; enable the interaction’s replace option when Back should leave the page immediately rather than replaying every pan.
  • Because Link mutates the URL directly via the browser History API outside the Angular Router, coordinate router navigation carefully if both manage query parameters.

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.