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.

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.tsimport { 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();
}
} 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-spy.react.tsximport { useEffect, useRef, useState } from 'react';
import { getTopLeft, getWidth } from 'ol/extent';
import { EXTENT } from 'ol/proj/epsg3857';
import type OLMap from 'ol/Map';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import type { Pixel } from 'ol/pixel';
import { getRenderPixel } from 'ol/render';
import type RenderEvent from 'ol/render/Event';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
Map,
OSMSource,
TileLayer,
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}`);
/** A spyglass that shows the orthophoto through the street map around the pointer; the arrow keys resize it. */
export function LayerSpy() {
const tileGrid = useWMTSTileGrid({ origin, resolutions, matrixIds });
const [radius, setRadius] = useState(75);
/** The radius the next frame draws with, set before the map is asked to render. */
const currentRadius = useRef(75);
const mousePosition = useRef<Pixel | null>(null);
const map = useRef<OLMap>(null);
/** Clips the orthophoto to a circle around the pointer before it is drawn. */
const clip = (event: RenderEvent): void => {
const context = event.context as CanvasRenderingContext2D;
context.save();
context.beginPath();
const position = mousePosition.current;
if (position) {
const radius = currentRadius.current;
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();
};
const restore = (event: RenderEvent): void => {
(event.context as CanvasRenderingContext2D).restore();
};
const move = (event: MapBrowserEvent): void => {
mousePosition.current = event.pixel;
map.current?.render();
};
const leave = (): void => {
mousePosition.current = null;
map.current?.render();
};
useEffect(() => {
const resize = (event: KeyboardEvent): void => {
if (event.key === 'ArrowUp') currentRadius.current = Math.min(currentRadius.current + 5, 150);
else if (event.key === 'ArrowDown') currentRadius.current = Math.max(currentRadius.current - 5, 25);
else return;
setRadius(currentRadius.current);
map.current?.render();
event.preventDefault();
};
document.addEventListener('keydown', resize);
return () => document.removeEventListener('keydown', resize);
}, []);
return (
<>
<div onMouseOut={leave}>
<Map ref={map} height="480px" onPointerMove={move}>
<DefaultInteractions />
<DefaultControls />
<View zoom={13}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
<TileLayer onPreRender={clip} onPostRender={restore}>
<WMTSSource
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}
tileGrid={tileGrid}
/>
</TileLayer>
</Map>
</div>
<div className="example-controls">
<p className="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>
</>
);
}How the React version works
Around the cursor, the orthophoto shows through the street map in a circle; the up and down arrow keys change the radius from 25 to 150 pixels.
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.
From Angular to React
| Angular | React |
|---|---|
(pointerMove) on aol-map | onPointerMove on Map |
(mouseout)="leave()" on aol-map | <div onMouseOut={leave}> around Map, as in tooltip-on-hover |
host: { '(document:keydown)': … } | useEffect with a keydown listener on the document |
| class fields with the cursor position and the radius | useRef, read in prerender |
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 key listener belongs to the effect and goes away on unmount.
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 callsrender()to repaint the moving lens, while(mouseout)clears it when leaving the viewport.- Inside the orthophoto layer’s
[prerender],getRenderPixelconverts 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
documentprevents 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.
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.