名稱

ST_ClosestPoint — 傳回 g1 上最接近 g2 的 2D 點。這是從一個幾何圖形到另一個幾何圖形的最短線的第一個點。

概要

geometry ST_ClosestPoint(geometry geom1, geometry geom2);

geography ST_ClosestPoint(geography geom1, geography geom2, boolean use_spheroid = true);

描述

傳回 geom1 上最接近 geom2 的 2 維點。這是幾何圖形之間最短線的第一個點(由ST_ShortestLine計算)。

[Note]

如果您有 3D 幾何圖形,您可能會更喜歡使用 ST_3DClosestPoint

增強功能:3.4.0 - 支援地理位置。

可用性:1.5.0

範例

點和線串的最接近點是點本身。線串和點的最接近點是線上的點。

SELECT ST_AsText( ST_ClosestPoint(pt,line)) AS cp_pt_line,
       ST_AsText( ST_ClosestPoint(line,pt)) AS cp_line_pt
    FROM (SELECT 'POINT (160 40)'::geometry AS pt,
                 'LINESTRING (10 30, 50 50, 30 110, 70 90, 180 140, 130 190)'::geometry AS line ) AS t;

   cp_pt_line   |                cp_line_pt
----------------+------------------------------------------
 POINT(160 40)  | POINT(125.75342465753425 115.34246575342466)

多邊形 A 到多邊形 B 的最接近點

SELECT ST_AsText( ST_ClosestPoint(
		'POLYGON ((190 150, 20 10, 160 70, 190 150))',
		ST_Buffer('POINT(80 160)', 30)	)) As ptwkt;
------------------------------------------
 POINT(131.59149149528952 101.89887534906197)