PostGIS计算聚类,通常有种两种方法。一个是使用kmeans方法;另一种是使用阈值计算相对空间关系,实现聚类。
ST_ClusterKMeans是基于K均值算法,需要指定簇的数量(k值),根据点的位置进行划分。
ST_ClusterWithin是基于距离的聚类,它把互相在指定距离内的点归为一类,适合根据实际地理距离来分组。
本次分享的是第二种方法:基于ST_ClusterWithin方法,计算点之间的相对空间关系,实现聚类。
示例语法
SELECT row_number() over () AS id,
ST_NumGeometries(gc),
gc AS geom_collection,
ST_Centroid(gc) AS centroid,
ST_MinimumBoundingCircle(gc) AS circle,
sqrt(ST_Area(ST_MinimumBoundingCircle(gc)) / pi()) AS radius
FROM (
SELECT unnest(ST_ClusterWithin(geom, 100)) gc
FROM points_table
) f;
用法说明
子查询部分
SELECT unnest(ST_ClusterWithin(geom, 100)) gc
FROM points_table
ST_ClusterWithin(geom, 100)
将points_table表中距离不超过100单位的几何对象(如点)聚类,返回一个geometry[]数组,每个数组元素是一个几何集合(如MULTIPOINT)。
unnest()
将数组展开为多行,每行对应一个聚类的几何集合gc。
外层查询
SELECT
row_number() over () AS id,
ST_NumGeometries(gc),
gc AS geom_collection,
ST_Centroid(gc) AS centroid,
ST_MinimumBoundingCircle(gc) AS circle,
sqrt(ST_Area(ST_MinimumBoundingCircle(gc)) / pi()) AS radius
FROM (...) f;
row_number() over ()
生成递增的id。
ST_NumGeometries(gc)
统计几何集合中的对象数量(如点的个数)。
ST_Centroid(gc)
计算几何集合的质心。
ST_MinimumBoundingCircle(gc)
生成包含几何集合的最小外接圆(返回POLYGON)。
sqrt(ST_Area(...) / pi())
通过圆面积公式反推半径。
结果如图
