简体   繁体   English

找到两个彼此最接近的多边形

[英]Find two polygons closest to each other postgis

I have a table of buildings where they are all polygons and it looks something like this: 我有一张建筑物的桌子,它们都是多边形,看起来像这样:

Building_name | Building_ID | Geom
A             | 1           | *polygon object
B             | 2           | *polygon object
C             | 3           | *polygon object

How do I find which 2 buildings are closest to each other using straight-line distance? 如何使用直线距离找到哪两个建筑物最接近?

Output should be for example: A and B are the buildings closest to each other. 输出应为例如:A和B是彼此最近的建筑物。

Is this possible for polygons? 多边形可能吗?

Thanks in advance! 提前致谢!

SELECT
    a."Building_name" "Building name A",
    b."Building_name" "Building name B",
    ST_Distance(a."Geom", b."Geom") distance
FROM
    polygons a, polygons b
WHERE
    a."Building_ID" <> b."Building_ID"
    -- optionally add a ST_DWithin condition to improve performance:
    -- AND ST_DWithin(a."Geom", b."Geom", 1000)    
ORDER BY
    distance
LIMIT 1;

ST_Distance calculates the shortest line distance (in SRID units), while ST_ShortestLine returns the actual geometry of the shortest line. ST_Distance计算最短线的距离(以SRID单位),而ST_ShortestLine返回最ST_ShortestLine的实际几何形状。

For sample geometry collection 用于样品几何采集

在此处输入图片说明

Following SQL would do slightly faster, compared to st_distance, on large number of geometries, since it makes use of closest neighbor index. 与st_distance相比,在大量几何图形上执行SQL会稍快一些,因为它使用了最邻近索引。 Besides, you might consider 'true' as your third st_distance parameter in order to get spherical distance, if you decide, for whatever reason, to use one. 此外,如果出于任何原因决定使用一个,则可以将“ true”作为第三个st_distance参数以获得球面距离。

select x1.name, x2.name
from (values (1,'A',st_geomfromtext('Polygon ((325 708, 348 768, 424 758, 481 653, 421 589, 340 628, 325 708))')),
(2,'B',st_geomfromtext('Polygon ((643 891, 692 808, 769 825, 793 885, 786 923, 730 939, 705 902, 643 891))')),
(3,'C',st_geomfromtext('Polygon ((692 620, 669 553, 767 523, 882 548, 893 622, 834 683, 692 620))')),
(4,'D',st_geomfromtext('Polygon ((519 703, 549 676, 586 707, 585 751, 555 778, 526 745, 519 703))'))) x1(id,name,geom)
join (values (1,'A',st_geomfromtext('Polygon ((325 708, 348 768, 424 758, 481 653, 421 589, 340 628, 325 708))')),
(2,'B',st_geomfromtext('Polygon ((643 891, 692 808, 769 825, 793 885, 786 923, 730 939, 705 902, 643 891))')),
(3,'C',st_geomfromtext('Polygon ((692 620, 669 553, 767 523, 882 548, 893 622, 834 683, 692 620))')),
(4,'D',st_geomfromtext('Polygon ((519 703, 549 676, 586 707, 585 751, 555 778, 526 745, 519 703))'))) x2(id,name,geom)
on x1.id<>x2.id
order by x1.geom<->x2.geom
limit 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM