ST_ClusterWithin

更新时间:
复制 MD 格式

Groups geometry objects into clusters based on a distance threshold, and returns the clusters as an array of GeometryCollection objects.

Syntax

geometry[] ST_ClusterWithin(geometry set g, float8 distance);

Parameters

ParameterTypeDescription
ggeometry setThe geometry objects to cluster.
distancefloat8The distance to use for clustering.

Usage notes

The distance parameter is a Cartesian distance expressed in the units of the Spatial Reference Identifier (SRID) of the input geometry objects.

Examples

Example 1: Cluster with a maximum distance of 1

Four geometry objects — three LINESTRINGs and one POINT — are grouped into two clusters.

SELECT ST_AsText(unnest(ST_ClusterWithin(geom, 1)))
  FROM (SELECT ARRAY['LINESTRING (0 0,0 1)'::geometry,
                     'LINESTRING (2 3,3 3)'::geometry,
                     'LINESTRING (0 1,2 3)'::geometry,
                     'POINT (-1 -1)'::geometry] AS geom) AS test;

Output:

                              st_astext
---------------------------------------------------------------
 GEOMETRYCOLLECTION(LINESTRING(0 0,0 1),LINESTRING(2 3,3 3),LINESTRING(0 1,2 3))
 GEOMETRYCOLLECTION(POINT(-1 -1))
(2 rows)

Example 2: Cluster with a maximum distance of 2

With the distance threshold increased to 2, all four geometry objects merge into a single cluster.

SELECT ST_AsText(unnest(ST_ClusterWithin(geom, 2)))
  FROM (SELECT ARRAY['LINESTRING (0 0,0 1)'::geometry,
                     'LINESTRING (2 3,3 3)'::geometry,
                     'LINESTRING (0 1,2 3)'::geometry,
                     'POINT (-1 -1)'::geometry] AS geom) AS test;

Output:

                              st_astext
---------------------------------------------------------------
 GEOMETRYCOLLECTION(LINESTRING(0 0,0 1),LINESTRING(2 3,3 3),LINESTRING(0 1,2 3),POINT(-1 -1))
(1 row)