Layers · Angular, React and OpenLayers

A spyglass from one layer into another

Create an interactive OpenLayers spyglass lens revealing aerial orthophotography inside a cursor-following circular aperture over OpenStreetMap.

A street map of Kraków at zoom 13 with a circle of the orthophotomap around the pointer on the Main Square.
A screenshot of the example. Orthophotomap © GUGiK. Map data © OpenStreetMap contributors.

What this example shows

Over a street map of central Kraków at zoom 13, moving the mouse sweeps a crisp circular “spyglass” lens across the canvas that reveals GUGiK’s high-resolution aerial orthophotomap strictly underneath the pointer while keeping surrounding streets in OpenStreetMap style.

Pressing the Up and Down arrow keys enlarges or shrinks the inspection lens between 25 and 150 pixels in 5-pixel increments, and moving the cursor off the map hides the lens cleanly.

When you need it

Spot-checking roof outlines, tree canopies or driveway entrances under a street map is often fastest through a localized cursor lens that preserves street-name context everywhere else on screen.

Unlike toggling layer opacity—which washes out both layers—a circular clip aperture shows 100%-opaque imagery exactly at your point of focus.

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-spy.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import { getTopLeft, getWidth } from 'ol/extent';
import { EXTENT } from 'ol/proj/epsg3857';
import type { Pixel } from 'ol/pixel';
import { getRenderPixel } from 'ol/render';
import type RenderEvent from 'ol/render/Event';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  MapComponent,
  SourceOsmComponent,
  SourceTileWMTSComponent,
  TileGridWMTSComponent,
  ViewComponent,
} from 'cc-openlayers';

const size = getWidth(EXTENT) / 256;

/** A spyglass that shows the orthophoto through the street map around the pointer; the arrow keys resize it. */
@Component({
  selector: 'app-layer-spy',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    MapComponent,
    SourceOsmComponent,
    SourceTileWMTSComponent,
    TileGridWMTSComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { '(document:keydown)': 'resize($event)' },
  template: `
    <aol-map height="480px" (pointerMove)="move($event)" (mouseout)="leave()">
      <aol-interaction-default />
      <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-layer-tile [prerender]="clip" [postrender]="restore">
        <aol-source-tilewmts
          attributions='Tiles © <a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>'
          crossOrigin="anonymous"
          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-map>
    <div class="example-controls">
      <p class="example-hint">
        Move over the map to look through the street map. Use the ↑ and ↓ keys to resize the spyglass.
      </p>
      <label
        >Radius <output>{{ radius() }}</output></label
      >
    </div>
  `,
})
export class LayerSpy {
  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 readonly radius = signal(75);
  private readonly mousePosition = signal<Pixel | null>(null);
  private readonly map = viewChild.required(MapComponent);

  /** Clips the orthophoto to a circle around the pointer before it is drawn. */
  protected readonly clip = (event: RenderEvent): void => {
    const context = event.context as CanvasRenderingContext2D;
    context.save();
    context.beginPath();
    const position = this.mousePosition();
    if (position) {
      const radius = this.radius();
      const pixel = getRenderPixel(event, position);
      const offset = getRenderPixel(event, [position[0] + radius, position[1]]);
      const canvasRadius = Math.hypot(offset[0] - pixel[0], offset[1] - pixel[1]);
      context.arc(pixel[0], pixel[1], canvasRadius, 0, 2 * Math.PI);
      context.lineWidth = (5 * canvasRadius) / radius;
      context.strokeStyle = 'rgba(0,0,0,0.5)';
      context.stroke();
    }
    context.clip();
  };

  protected readonly restore = (event: RenderEvent): void => {
    (event.context as CanvasRenderingContext2D).restore();
  };

  protected move(event: MapBrowserEvent): void {
    this.mousePosition.set(event.pixel);
    this.map().instance.render();
  }

  protected leave(): void {
    this.mousePosition.set(null);
    this.map().instance.render();
  }

  protected resize(event: KeyboardEvent): void {
    if (event.key === 'ArrowUp') this.radius.update((radius) => Math.min(radius + 5, 150));
    else if (event.key === 'ArrowDown') this.radius.update((radius) => Math.max(radius - 5, 25));
    else return;
    this.map().instance.render();
    event.preventDefault();
  }
}

Architecture and OpenLayers mechanics

(pointerMove) records the latest CSS pointer pixel and triggers render(), while (mouseout) resets the stored coordinate to null so the lens disappears when the cursor leaves the map. In the upper orthophotomap layer’s [prerender] hook, getRenderPixel converts both the cursor position and an offset point one radius away into backing-canvas pixels—preserving exact visual circle size across Retina pixel ratios and rotated views.

The [prerender] handler strokes a subtle dark border ring and clips the 2D canvas context to that circle before aerial tiles paint; [postrender] restores the unclipped state afterward.

How it works

  • (pointerMove) updates the cursor pixel and calls render() to repaint the moving lens, while (mouseout) clears it when leaving the viewport.
  • Inside the orthophoto layer’s [prerender], getRenderPixel converts CSS pointer coordinates and radius offsets into backing-canvas pixels at any HiDPI scale or view rotation.
  • When the pointer is outside the map, clipping to an empty path suppresses aerial imagery completely without toggling layer state.
  • Document Up and Down arrow handlers step the spyglass radius by 5 pixels between 25 px and 150 px.

Pitfalls

  • Attaching Up/Down arrow listeners globally on document prevents normal arrow-key page scrolling and intercepts keys inside form inputs—scope keyboard shortcuts to a focused container in multi-control pages.
  • Canvas clipping hides pixels visually without restricting network fetches: the hidden orthophoto layer still downloads tiles across the full viewport.
  • Touch screens lack passive cursor hover, so dragging a finger moves the lens and pans the map simultaneously unless panning is temporarily locked.

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.