我正在尝试在空间表中的所有多边形之间执行递归交集,并获取生成的(多)多边形以及每个多边形的每个交集的信息。

一个图像(不是真的按比例)来解释它:
sql - 多边形之间的PostGIS递归交集-LMLPHP

假设表中有 A, B, C 个方格。我想在输出中有 A, B, C, A+B, A+C, B+C, A+B+C 个多边形,我需要知道 A+BAB 等的交集。

到目前为止,我有一个执行相交的查询,但它没有“切断”原始多边形的相交部分。例如:

Polygon A should be      A - (A+B) - (A+C) - (A+B+C)
Polygon A+C should be    A+C - (A+B+C)

我现在得到的 AA+C 多边形的结果图像:

sql - 多边形之间的PostGIS递归交集-LMLPHP

这是一个测试脚本,使用图像中的方块作为数据。查看 area 列,很明显缺少一些递归 ST_Difference,我只是不知道如何。欢迎任何想法。
-- Create a test table
CREATE TABLE test (
    name text PRIMARY KEY,
    geom geometry(POLYGON)
);

-- Insert test data
INSERT INTO test (name, geom) VALUES
    ('A', ST_GeomFromText('POLYGON((1 2, 1 6, 5 6, 5 2, 1 2))')),
    ('B', ST_GeomFromText('POLYGON((0 0, 0 4, 4 4, 4 0, 0 0))')),
    ('C', ST_GeomFromText('POLYGON((2 0, 2 4, 6 4, 6 0, 2 0))'));


-- Query
WITH RECURSIVE
source (rownum, geom, ret) AS (
    SELECT row_number() OVER (ORDER BY name ASC), ST_Multi(geom), ARRAY[name] FROM test
),
r (rownum, geom, ret, incroci) AS (
    SELECT rownum, geom, ret, 0 FROM source
    UNION ALL
    SELECT s.rownum, ST_CollectionExtract(ST_Intersection(s.geom, r.geom), 3), (r.ret || s.ret), (r.incroci + 1)
        FROM source AS s INNER JOIN r ON s.rownum > r.rownum AND ST_Intersects(s.geom, r.geom) AND ST_Area(ST_Intersection(s.geom, r.geom)) > 0.5
),
result (geom, ret) AS (
    SELECT ST_Union(geom) AS geom, ret FROM r GROUP BY ret
)
SELECT geom, ST_Area(geom) AS area, ret FROM result ORDER BY ret

当然,在这个特定的例子中窗口函数并不是绝对必要的,但是这段代码是我真实案例的简化版本,它在侧面做了一些更多的事情。

我正在使用 PostgreSQL 9.2 和 PostGIS 2.0

最佳答案

ST_DIFFRENCE 不必是递归的,您已经拥有所有多边形,因此您必须从每个 geom 中减去包含该 ret 但不等于它的其他 geom 的并集。这是有效的,所以你应该这样做:

    WITH RECURSIVE
source (rownum, geom, ret) AS (
    SELECT row_number() OVER (ORDER BY name ASC), ST_Multi(geom), ARRAY[name] FROM test
),
r (rownum, geom, ret, incroci) AS (
    SELECT rownum, geom, ret, 0 FROM source
    UNION ALL
    SELECT s.rownum, ST_CollectionExtract(ST_Intersection(s.geom, r.geom), 3), (r.ret || s.ret), (r.incroci + 1)
        FROM source AS s INNER JOIN r ON s.rownum > r.rownum AND ST_Intersects(s.geom, r.geom) AND ST_Area(ST_Intersection(s.geom, r.geom)) > 0.5
),
result (geom, ret) AS (
    SELECT ST_Difference(ST_Union(r.geom),q.geom) AS geom, r.ret FROM r JOIN (SELECT r.ret,ST_UNION(COALESCE(r2.geom,ST_GeomFromText('POLYGON EMPTY'))) as geom FROM r LEFT JOIN r AS r2 ON r.ret<@r2.ret AND r.ret!=r2.ret GROUP BY r.ret) AS q on r.ret=q.ret GROUP BY r.ret,q.geom
)
SELECT geom, ST_Area(geom) AS area, ret FROM result ORDER BY ret

关于sql - 多边形之间的PostGIS递归交集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15620529/

10-15 20:34