Vector data · Angular, React and OpenLayers

Cluster hulls and expanded members

Inspect dynamic OpenLayers point clusters through hover convex-hull polygons, click-to-zoom bounds and fanned-out overlapping member markers.

Inspect clustered points through convex hulls, zooming and expanded overlapping members.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Over Kraków on OpenStreetMap with a live cluster-distance slider (starting at 35 px), hovering any multi-point cluster reveals the exact geographic convex-hull polygon enclosing its hidden members, while clicking zooms smoothly into wide clusters or fans tightly colocated points outward with leader lines.

When you need it

Standard numbered cluster circles give no clue whether grouped incidents span ten city blocks or share one building address—and zooming to maximum level still leaves co-located points stacked on top of one another.

Combining hover convex hulls with click-to-zoom and spider/fan expansion solves dense point exploration end to end.

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.

clusters-dynamic.html
<aol-map height="480px"
  ><aol-control-defaults /><aol-interaction-default /><aol-view [zoom]="13" [maxZoom]="19"
    ><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
    >Cluster distance
    <input type="range" min="0" max="100" [value]="distance()" (input)="setDistance($event)" /><output>{{
      distance()
    }}</output></label
  >
  <p class="example-hint">Hover a cluster for its hull; click to zoom or expand overlapping members.</p>
</div>
clusters-dynamic.shared.ts
import hull from 'monotone-chain-convex-hull';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import Polygon from 'ol/geom/Polygon';
import LineString from 'ol/geom/LineString';
import Cluster from 'ol/source/Cluster';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import Style from 'ol/style/Style';
import Circle from 'ol/style/Circle';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Text from 'ol/style/Text';
import type Map from 'ol/Map';
import { fromLonLat } from 'ol/proj';
import { createEmpty, extend, getWidth, getHeight } from 'ol/extent';
import { unByKey } from 'ol/Observable';
export function hullRing(points: number[][]): number[][] {
  const ring = hull(points.map((p) => [p[0], p[1]] as [number, number]));
  return ring.length ? [...ring, ring[0]] : [];
}
export function circlePoints(count: number, center: number[], resolution: number): number[][] {
  const radius = Math.max((28 * (2 + count)) / (2 * Math.PI), 35) * resolution;
  return Array.from({ length: count }, (_, i) => [
    center[0] + radius * Math.cos(Math.PI / 2 + (i * 2 * Math.PI) / count),
    center[1] + radius * Math.sin(Math.PI / 2 + (i * 2 * Math.PI) / count),
  ]);
}
const stroke = new Stroke({ color: '#c50', width: 2 });
const memberStyle = (geometry?: Point) =>
  new Style({ geometry, image: new Circle({ radius: 7, fill: new Fill({ color: '#fa3' }), stroke }) });
export function dynamicClusters() {
  const members = Array.from(
    { length: 72 },
    (_, i) =>
      new Feature(new Point(fromLonLat([19.9368 + Math.sin(i * 2.4) * 0.018, 50.0614 + Math.cos(i * 1.8) * 0.011])))
  );
  members.push(...Array.from({ length: 5 }, () => new Feature(new Point(fromLonLat([19.9368, 50.0614])))));
  const source = new Cluster({ distance: 35, source: new VectorSource({ features: members }) });
  let hover: Feature | undefined, clicked: Feature | undefined, clickResolution: number | undefined;
  const hulls = new VectorLayer({
    source,
    style: (f) =>
      f === hover
        ? new Style({
            geometry: new Polygon([
              hullRing((f.get('features') as Feature<Point>[]).map((p) => p.getGeometry()?.getCoordinates() ?? [])),
            ]),
            fill: new Fill({ color: 'rgba(255,153,0,.3)' }),
            stroke,
          })
        : undefined,
  });
  const clusters = new VectorLayer({
    source,
    style: (f) => {
      const size = (f.get('features') as Feature[]).length;
      return size === 1
        ? memberStyle()
        : new Style({
            image: new Circle({ radius: 18, fill: new Fill({ color: '#e80' }), stroke }),
            text: new Text({ text: String(size), fill: new Fill({ color: '#fff' }) }),
          });
    },
  });
  const circles = new VectorLayer({
    source,
    style: (f, resolution) => {
      if (f !== clicked || resolution !== clickResolution) return undefined;
      const center = (f.getGeometry() as Point).getCoordinates();
      return circlePoints((f.get('features') as Feature[]).length, center, resolution).flatMap((p) => [
        new Style({ geometry: new LineString([center, p]), stroke }),
        memberStyle(new Point(p)),
      ]);
    },
  });
  function bind(map: Map) {
    const keys = [
      map.on('pointermove', (event) => {
        hover = event.dragging
          ? undefined
          : map.forEachFeatureAtPixel(event.pixel, (f) => f as Feature, { layerFilter: (l) => l === clusters });
        hulls.changed();
        const target = map.getTargetElement();
        if (target) target.style.cursor = hover ? 'pointer' : '';
      }),
      map.on('click', (event) => {
        const f = map.forEachFeatureAtPixel(event.pixel, (f) => f as Feature, { layerFilter: (l) => l === clusters });
        if (!f) return;
        const members = f.get('features') as Feature<Point>[];
        if (members.length < 2) return;
        const extent = createEmpty();
        members.forEach((m) => extend(extent, m.getGeometry()?.getExtent() ?? []));
        const view = map.getView(),
          resolution = view.getResolution() ?? 1;
        if (view.getZoom() === view.getMaxZoom() || (getWidth(extent) < resolution && getHeight(extent) < resolution)) {
          clicked = f;
          clickResolution = resolution;
          circles.changed();
        } else {
          clicked = undefined;
          circles.changed();
          view.fit(extent, { duration: 500, padding: [50, 50, 50, 50] });
        }
      }),
    ];
    return () => {
      unByKey(keys);
      const target = map.getTargetElement();
      if (target) target.style.cursor = '';
    };
  }
  return { source, hulls, clusters, circles, bind };
}
clusters-dynamic.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, OnDestroy, signal, viewChild } from '@angular/core';
import {
  MapComponent,
  ViewComponent,
  CoordinateComponent,
  LayerTileComponent,
  SourceOsmComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
} from 'cc-openlayers';
import { dynamicClusters } from './clusters-dynamic.shared';

@Component({
  selector: 'app-clusters-dynamic',
  imports: [
    MapComponent,
    ViewComponent,
    CoordinateComponent,
    LayerTileComponent,
    SourceOsmComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './clusters-dynamic.html',
})
export class ClustersDynamic implements AfterViewInit, OnDestroy {
  private readonly map = viewChild.required(MapComponent);
  private readonly demo = dynamicClusters();
  readonly distance = signal(35);
  private cleanup = () => {};
  ngAfterViewInit(): void {
    const map = this.map().instance,
      layers = [this.demo.hulls, this.demo.clusters, this.demo.circles];
    layers.forEach((l) => map.addLayer(l));
    const unbind = this.demo.bind(map);
    this.cleanup = () => {
      unbind();
      layers.forEach((l) => map.removeLayer(l));
    };
  }
  ngOnDestroy(): void {
    this.cleanup();
  }
  setDistance(e: Event): void {
    this.distance.set((e.target as HTMLInputElement).valueAsNumber);
    this.demo.source.setDistance(this.distance());
  }
}

Architecture and OpenLayers mechanics

Three coordinated vector layers mount on the map (hulls, clusters and expanded circles), backed by a cluster source whose pixel distance updates via setDistance. Hovering computes the member points’ outer boundary ring with monotone-chain-convex-hull, clicking wide clusters fits their extent, clicking tight clusters displaces overlapping members radially so each can be inspected individually, and ngOnDestroy unbinds events and removes layers cleanly.

How it works

  • Hovering computes and draws each cluster’s spatial envelope with monotone-chain-convex-hull, while clicking either zooms to the cluster extent or separates closely overlapping members.

Pitfalls

  • Because OpenLayers clusters points by screen-pixel distance, both cluster membership and convex-hull shapes regroup dynamically whenever view zoom resolution changes.

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.