shadcn-svelte map
DocsComponentsBlocks
Get Started
  • Introduction
  • Installation
Guides
  • Theming
  • Drawing
  • Accessibility
  • Performance
  • Content Security Policy
Core
  • Map
  • Control Container
Markers
  • Marker
  • Popup
  • Point Layer
Data
  • GeoJSON
  • Shapes
  • Route
  • Arc
  • Cluster Layer
  • Heatmap
Controls
  • Zoom Control
  • Compass Control
  • Scale Control
  • Fullscreen Control
  • Locate Control
  • Basemap Control
  • Search Control
  • Draw Control
More
  • Place Autocomplete
  • Utilities

Cluster Layer

Previous Next

Group nearby points into counted clusters that split apart as you zoom in.

<script lang="ts">
	import type { Feature, FeatureCollection, Point } from 'geojson';
	import { Map, MapClusterLayer, type MapClusterClick } from '$lib/components/ui/map/index.js';

	interface Stand {
		name: string;
		bikes: number;
	}

	const SEED = 7;
	const COUNT = 400;
	const CENTER: [number, number] = [2.3488, 48.8534];
	const SPREAD = 0.06;
	/** Latitude degrees are longer than longitude degrees in Paris, so spread less north to south. */
	const LAT_SQUASH = 0.7;
	const MAX_BIKES = 20;

	/** A small seeded generator, so every load shows the same stands. */
	function seeded(seed: number): () => number {
		let state = seed;
		return () => {
			state = (state * 16807) % 2147483647;
			return (state - 1) / 2147483646;
		};
	}

	function stands(): FeatureCollection<Point, Stand> {
		const random = seeded(SEED);
		const spread = () => (random() + random() + random() - 1.5) * SPREAD;
		const features = Array.from({ length: COUNT }, (_, index): Feature<Point, Stand> => ({
			type: 'Feature',
			properties: { name: `Stand ${index + 1}`, bikes: Math.floor(random() * MAX_BIKES) },
			geometry: {
				type: 'Point',
				coordinates: [CENTER[0] + spread(), CENTER[1] + spread() * LAT_SQUASH]
			}
		}));
		return { type: 'FeatureCollection', features };
	}

	const data = stands();
	let message = $state('Click a cluster or a stand');

	function showCluster(cluster: MapClusterClick) {
		message = `${cluster.count} stands here`;
	}

	function showStand(stand: Feature<Point, Stand>) {
		message = `${stand.properties.name}: ${stand.properties.bikes} bikes free`;
	}
</script>

<div class="relative size-full">
	<Map class="size-full" viewport={{ center: CENTER, zoom: 11, bearing: 0, pitch: 0 }}>
		<MapClusterLayer {data} onclusterclick={showCluster} onclick={showStand} />
	</Map>
	<p
		class="absolute top-3 left-3 rounded-md bg-background/90 px-2 py-1 text-xs shadow"
		aria-live="polite"
	>
		{message}
	</p>
</div>

MapClusterLayer takes a GeoJSON feature collection of points and groups the ones that sit close together on screen. Each group shows as a circle with a count. Circles grow at 10, 100 and 1000 points. Zoom in and the clusters split until single points show.

Clustering runs in MapLibre’s worker, so thousands of points stay smooth.

Usage

<script lang="ts">
	import type { FeatureCollection, Point } from 'geojson';
	import { Map, MapClusterLayer } from '$lib/components/ui/map/index.js';

	let { stands }: { stands: FeatureCollection<Point, { name: string }> } = $props();
	let selected = $state('');
</script>

<Map class="h-96">
	<MapClusterLayer data={stands} onclick={(stand) => (selected = stand.properties.name)} />
</Map>

Grouping

clusterRadius is the distance in pixels within which points join a cluster. It defaults to 50. Above clusterMaxZoom, which defaults to 14, points are never grouped. Changing either regroups the points in place, without rebuilding the layer.

Changing data updates the source in place, so you can filter points without remounting the layer.

Clicks

Clicking a cluster zooms in until it splits. Set zoomOnClick={false} to keep the camera still. onclusterclick gets the cluster id, the number of points in it and its position.

Clicking a single point calls onclick with the original feature from data and its index, so any properties you stored come back as you passed them. The cursor turns into a pointer over clusters and points.

Keyboard

The single points are offered to keyboard and screen reader users as a list, one tab stop on the map. Choosing a point with Enter zooms in until it stands on its own and calls onclick, the same as a click. Name points with featureLabel and the list with listLabel, or turn it off with keyboard={false}.

Labels

On styles that ship glyphs, which includes every built-in basemap, the counts are drawn by MapLibre in the font stack from font. It defaults to DEFAULT_CLUSTER_FONT, which is ['Noto Sans Regular'], a font OpenFreeMap serves. If you use another style, pass a font stack that style’s glyph server has.

If the style has no glyphs URL at all, MapLibre cannot draw text. The counts are then drawn as HTML on top of the circles, in the page font, and follow the map as it moves. They are hidden from screen readers, since they repeat what the circle shows.

API Reference

MapClusterLayer

Props

NameTypeDescription
data required FeatureCollection<Point, P>Points to cluster. Changing it updates the source in place.
id stringSource id; layers are `<id>-clusters`, `<id>-count` and `<id>-points`. Read once.
clusterRadius numberPixel radius points are grouped within. Changing it regroups in place. Defaults to 50.
clusterMaxZoom numberAbove this zoom points are never grouped. Changing it regroups in place. Defaults to 14.
color stringCluster circles. Defaults to the theme's `--primary`.
textColor stringCluster counts. Defaults to the theme's `--primary-foreground`.
pointColor stringSingle points. Defaults to `color`.
pointRadius numberSingle point radius in pixels. Defaults to 5.
font string[]Font stack of the counts on styles that ship glyphs. Read once. On styles without glyphs the counts are drawn as HTML in the page font instead. Defaults to DEFAULT_CLUSTER_FONT.
zoomOnClick booleanZoom in on a cluster when it is clicked. Defaults to true.
beforeId stringDraw below this layer when it exists; changing it moves the layers.
keyboard booleanOffer the single points to keyboard and screen reader users as a list, one tab stop on the map. Choosing one zooms in until it stands alone and calls `onclick`. Defaults to true.
listLabel stringAccessible name of the keyboard list, such as "Stores". Defaults to 'Points'.
featureLabel (feature: PointFeature, index: number) => stringName of a point in the keyboard list. Defaults to its `name` property.

Events

NameTypeDescription
onclick (feature: PointFeature, index: number) => voidCalled with a clicked single point and its index in `data.features`.
onclusterclick (cluster: MapClusterClick) => voidCalled when a cluster is clicked.
Arc Heatmap

On This Page

UsageGroupingClicksKeyboardLabelsAPI Reference

Handcrafted by Oggy. The source code is on GitHub.