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.

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.tsimport 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.tsimport { 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());
}
} 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.
clusters-dynamic.react.tsximport { useEffect, useState } from 'react';
import { Map, View, Coordinate, TileLayer, OSMSource, DefaultControls, DefaultInteractions } from 'cc-openlayers/react';
import type OLMap from 'ol/Map';
import { dynamicClusters } from './clusters-dynamic.shared';
export function ClustersDynamic() {
const [map, setMap] = useState<OLMap | null>(null);
const [demo] = useState(dynamicClusters);
const [distance, setDistance] = useState(35);
useEffect(() => {
if (!map) return;
const layers = [demo.hulls, demo.clusters, demo.circles];
layers.forEach((l) => map.addLayer(l));
const unbind = demo.bind(map);
return () => {
unbind();
layers.forEach((l) => map.removeLayer(l));
};
}, [map, demo]);
return (
<>
<Map ref={setMap} height="480px">
<DefaultControls />
<DefaultInteractions />
<View zoom={13} maxZoom={19}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
</Map>
<div className="example-controls">
<label>
Cluster distance{' '}
<input
type="range"
min="0"
max="100"
value={distance}
onChange={(e) => {
const distance = e.currentTarget.valueAsNumber;
setDistance(distance);
demo.source.setDistance(distance);
}}
/>
<output>{distance}</output>
</label>
<p className="example-hint">Hover a cluster for its hull; click to zoom or expand overlapping members.</p>
</div>
</>
);
}clusters-dynamic.shared.tsimport 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 };
}How the React version works
Inspect clustered points through convex hulls, zooming and expanded overlapping members.
What both versions share
monotone-chain-convex-hull computes the cluster outline. Hover reveals the hull; clicking zooms or separates nearby members.
From Angular to React
| Angular | React |
|---|---|
| Signals and template bindings update the cluster distance. | useState and event handlers update the same distance. |
| An external Angular template declares the example. | JSX declares the example and its controls. |
| The Angular lifecycle releases the mounted resources. | Effect or subscription cleanup releases the mounted resources. |
Who creates, updates and disposes
The cluster source, hull style, expanded members and map event bindings are shared. Cleanup detaches the layers and listeners.
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.
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.