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.

Gray points with green rims over Kraków's Old Town at zoom 13 on OpenStreetMap, with a yellow ring and line from the pointer to the nearest point.
A screenshot of the example. Map data © OpenStreetMap contributors.

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

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.
  • getClosestFeatureToCoordinate queries the source R-tree for the nearest point, drawn with a connector line inside postrender.
  • hasFeatureAtPixel updates 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.

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.