Clustering and statistics
Quick answer
This tutorial compares turf.clustersDbscan, which groups points by density using maxDistance and minPoints, with turf.clustersKmeans, which splits points into a fixed numberOfClusters. It shows the core, edge and noise labels DBSCAN writes into properties.dbscan, and how clusterEach, collect and tag turn a cluster id into per-group statistics. You will be able to group points and summarize each group.
Key points
- Set maxDistance in the units option, where 0.5 to 2 kilometers suits city-scale point sets.
- Iterate groups with turf.clusterEach(clustered, 'cluster', callback) rather than manual grouping.
- Use turf.collect to gather one property per group and then write aggregates back onto points.
Example
var clustered = turf.clustersDbscan(points, 1.5, {
units: 'kilometers',
minPoints: 3,
mutate: true // 直接改原点集,不额外复制
});
var noise = clustered.features.filter(function (p) {
return p.properties.cluster === undefined;
});
console.log('组数', new Set(clustered.features
.map(function (p) { return p.properties.cluster; })
.filter(function (c) { return c !== undefined; })).size);
console.log('噪声点', noise.length);var groups = [];
turf.clusterEach(clustered, 'cluster', function (cluster, features) {
var fc = turf.featureCollection(features);
var box = turf.bboxPolygon(turf.bbox(fc));
var mid = turf.center(fc);
var sum = features.reduce(function (s, f) {
return s + (f.properties.value || 0);
}, 0);
groups.push({
cluster: cluster,
count: features.length,
total: sum,
center: turf.getCoord(mid),
bbox: turf.bbox(fc)
});
});
console.log(groups);
Notes
- mutate: true edits the original point set, so clone first when the raw data is needed elsewhere.
- Convex hulls around KMeans groups can enclose large empty areas that contain no points.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Clustering and statistics. https://www.jingweizhi.com/en/turf/tutorials/clustering.html (accessed 2026-11-03).