Vector data · Angular, React and OpenLayers
Twenty thousand points with snapping
Render 20,000 seeded vector points smoothly in OpenLayers using two shared styles and snap a postrender indicator line to the nearest feature.

What this example shows
Twenty thousand points in two circle sizes blanket Kraków and its surroundings over OpenStreetMap while maintaining responsive panning, cursor hit-testing and real-time nearest-neighbour snapping—drawing a yellow highlight ring and connector line from the cursor to the closest point on every pointer move.
When you need it
Address registers, tree inventories, utility poles and LiDAR sample previews routinely push client-side vector layers to 10,000–50,000 points where naive per-feature styling stalls the browser.
Benchmarking 20,000 points demonstrates how shared Style instances and R-tree spatial indexing keep both rendering and nearest-point queries instantaneous.
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.
synthetic-points.tsimport { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceOsmComponent,
SourceVectorComponent,
ViewComponent,
} from 'cc-openlayers';
import type { Coordinate } from 'ol/coordinate';
import Feature from 'ol/Feature';
import LineString from 'ol/geom/LineString';
import Point from 'ol/geom/Point';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import { fromLonLat } from 'ol/proj';
import type RenderEvent from 'ol/render/Event';
import { getVectorContext } from 'ol/render';
import type VectorSource from 'ol/source/Vector';
import CircleStyle from 'ol/style/Circle';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
const point = (radius: number) =>
new Style({
image: new CircleStyle({
radius,
fill: new Fill({ color: '#666666' }),
stroke: new Stroke({ color: '#bada55', width: 1 }),
}),
});
const styles: Record<number, Style> = { 10: point(5), 20: point(10) };
const snapStroke = new Stroke({ color: 'rgba(255,255,0,0.9)', width: 3 });
const snapStyle = new Style({ stroke: snapStroke, image: new CircleStyle({ radius: 10, stroke: snapStroke }) });
/** The nearest feature and the line to it, drawn above the layer while the pointer moves or clicks. */
interface Snap {
point: Point;
line: LineString;
}
/**
* Twenty thousand points in two sizes over a box around Kraków, drawn over OpenStreetMap; the closest one is snapped
* to under the pointer. The map starts close in over the Old Town, where the streets show between the points: the
* whole box is a solid block of them.
*/
@Component({
selector: 'app-synthetic-points',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceOsmComponent,
SourceVectorComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px" (pointerMove)="move($event)" (olClick)="displaySnap($event.coordinate)">
<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-vector [style]="pointStyle" [postrender]="drawSnap">
<aol-source-vector [wrapX]="false" [loader]="loadPoints" />
</aol-layer-vector>
</aol-map>
`,
})
export class SyntheticPoints {
private readonly map = viewChild.required(MapComponent);
private readonly source = viewChild.required(SourceVectorComponent);
private readonly snap = signal<Snap | null>(null);
protected readonly pointStyle = (feature: { get(key: string): unknown }): Style =>
styles[feature.get('size') as number];
protected readonly loadPoints = function (this: VectorSource): void {
this.addFeatures(randomPoints(20000));
};
protected readonly drawSnap = (event: RenderEvent): void => {
const snap = this.snap();
if (!snap) return;
const context = getVectorContext(event);
context.setStyle(snapStyle);
context.drawGeometry(snap.point);
context.drawGeometry(snap.line);
};
protected move(event: MapBrowserEvent): void {
if (event.dragging) return;
const map = this.map().instance;
this.displaySnap(map.getEventCoordinate(event.originalEvent as MouseEvent));
const target = map.getTargetElement();
if (target) target.style.cursor = map.hasFeatureAtPixel(event.pixel) ? 'pointer' : '';
}
protected displaySnap(coordinate: Coordinate): void {
const closest = this.source().instance.getClosestFeatureToCoordinate(coordinate);
const geometry = closest?.getGeometry();
if (!geometry) {
this.snap.set(null);
} else {
const closestPoint = geometry.getClosestPoint(coordinate);
this.snap.set({ point: new Point(closestPoint), line: new LineString([coordinate, closestPoint]) });
}
this.map().instance.render();
}
}
/** Points inside a box around Kraków, half of them sized 10 and half 20, the same on every render. */
function randomPoints(count: number): Feature<Point>[] {
const random = mulberry32(42);
const [west, south] = fromLonLat([19.6, 49.9]);
const [east, north] = fromLonLat([20.3, 50.2]);
return Array.from(
{ length: count },
(_, i) =>
new Feature({
geometry: new Point([west + (east - west) * random(), south + (north - south) * random()]),
i,
size: i % 2 ? 10 : 20,
})
);
}
/** A small seeded pseudo-random generator. */
function mulberry32(seed: number): () => number {
return () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
} 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.
synthetic-points.react.tsximport { useRef } from 'react';
import type { Coordinate as OLCoordinate } from 'ol/coordinate.js';
import Feature from 'ol/Feature.js';
import LineString from 'ol/geom/LineString.js';
import Point from 'ol/geom/Point.js';
import type OLMap from 'ol/Map.js';
import type MapBrowserEvent from 'ol/MapBrowserEvent.js';
import { fromLonLat } from 'ol/proj.js';
import type RenderEvent from 'ol/render/Event.js';
import { getVectorContext } from 'ol/render.js';
import type OLVectorSource from 'ol/source/Vector.js';
import CircleStyle from 'ol/style/Circle.js';
import Fill from 'ol/style/Fill.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
Map,
OSMSource,
TileLayer,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
const point = (radius: number) =>
new Style({
image: new CircleStyle({
radius,
fill: new Fill({ color: '#666666' }),
stroke: new Stroke({ color: '#bada55', width: 1 }),
}),
});
const styles: Record<number, Style> = { 10: point(5), 20: point(10) };
const snapStroke = new Stroke({ color: 'rgba(255,255,0,0.9)', width: 3 });
const snapStyle = new Style({ stroke: snapStroke, image: new CircleStyle({ radius: 10, stroke: snapStroke }) });
/** The nearest feature and the line to it, drawn above the layer while the pointer moves or clicks. */
interface Snap {
point: Point;
line: LineString;
}
/** Points inside a box around Kraków, half of them sized 10 and half 20, the same on every render. */
function randomPoints(count: number): Feature<Point>[] {
const random = mulberry32(42);
const [west, south] = fromLonLat([19.6, 49.9]);
const [east, north] = fromLonLat([20.3, 50.2]);
return Array.from(
{ length: count },
(_, i) =>
new Feature({
geometry: new Point([west + (east - west) * random(), south + (north - south) * random()]),
i,
size: i % 2 ? 10 : 20,
})
);
}
/** A small seeded pseudo-random generator. */
function mulberry32(seed: number): () => number {
return () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const pointStyle = (feature: { get(key: string): unknown }): Style => styles[feature.get('size') as number];
const loadPoints = function (this: OLVectorSource): void {
this.addFeatures(randomPoints(20000));
};
/**
* Twenty thousand points in two sizes over a box around Kraków, drawn over OpenStreetMap; the closest one is snapped
* to under the pointer. The map starts close in over the Old Town, where the streets show between the points: the
* whole box is a solid block of them.
*/
export function SyntheticPoints() {
const map = useRef<OLMap>(null);
const source = useRef<OLVectorSource>(null);
// The snap is read while the layer renders, not by the markup, so it is a ref and `drawSnap` stays stable.
const snap = useRef<Snap | null>(null);
const drawSnap = (event: RenderEvent): void => {
const current = snap.current;
if (!current) return;
const context = getVectorContext(event);
context.setStyle(snapStyle);
context.drawGeometry(current.point);
context.drawGeometry(current.line);
};
const displaySnap = (coordinate: OLCoordinate): void => {
const closest = source.current?.getClosestFeatureToCoordinate(coordinate);
const geometry = closest?.getGeometry();
if (!geometry) {
snap.current = null;
} else {
const closestPoint = geometry.getClosestPoint(coordinate);
snap.current = { point: new Point(closestPoint), line: new LineString([coordinate, closestPoint]) };
}
map.current?.render();
};
const move = (event: MapBrowserEvent): void => {
if (event.dragging) return;
const current = map.current;
if (!current) return;
displaySnap(current.getEventCoordinate(event.originalEvent as MouseEvent));
const target = current.getTargetElement();
if (target) target.style.cursor = current.hasFeatureAtPixel(event.pixel) ? 'pointer' : '';
};
return (
<Map ref={map} height="480px" onPointerMove={move} onClick={(event) => displaySnap(event.coordinate)}>
<DefaultInteractions />
<DefaultControls />
<View zoom={13}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
<VectorLayer style={pointStyle} onPostRender={drawSnap}>
<VectorSource ref={source} wrapX={false} loader={loadPoints} />
</VectorLayer>
</Map>
);
}How the React version works
Twenty thousand points around Kraków; a click snaps to the nearest point and draws a line to it.
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.
From Angular to React
| Angular | React |
|---|---|
a source loader and [wrapX]="false" | <VectorSource loader wrapX={false}> |
(postRender) drawing the snap | onPostRender with the snap in a useRef, because it is only drawn |
(pointerMove) and viewChild of the map | onPointerMove (and onClick) on Map with useRef<OLMap>; the reading in useState |
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.
Architecture and OpenLayers mechanics
A deterministic mulberry32(42) generator populates 20,000 points across the Kraków region (19.6°–20.3° E, 49.9°–50.2° N). Instead of allocating 20,000 style objects, the style function returns one of two pre-built Style instances keyed by the feature’s size property (5 px or 10 px circles), with [wrapX]="false" preventing duplicate world copies.
On pointer motion, getClosestFeatureToCoordinate queries the VectorSource’s internal R-tree in logarithmic time, postrender paints the transient snap line and highlight ring directly onto the canvas without mutating source features, and hasFeatureAtPixel toggles the pointer cursor.
How it works
- Seeded generator
mulberry32(42)creates 20,000 reproducible points across the greater Kraków bounding box. - The style function reuses just two shared Style instances selected by each feature’s size value (10 or 20), drawn as 5 px or 10 px radius circles.
getClosestFeatureToCoordinatequeries the source R-tree for the nearest point, drawn with a connector line insidepostrender.hasFeatureAtPixelupdates cursor affordance whenever the pointer hovers directly over a point.
Pitfalls
- Allocating new Style(...) inside a style function for 20,000 features creates 20,000 garbage-collected objects on every pan frame—always return pre-allocated or cached Style references.
- Setting
[wrapX]="false"avoids multiplying 20,000 draw calls across repeated horizontal worlds when zoomed out.
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.