Postgres - 使用 postgis 计算距离

Postgres - Calculate distance with postgis

找了几天,试了所有的东西,我来问一下如何用PostGis在Postgres上计算两点之间的距离。我得到了一个 table 调用位置。这 table 得到了点类型的“坐标”列。当用户在应用程序中插入一个值时,我需要获取按关闭距离排序的位置。我知道我需要使用 ST_Distance,但每次我尝试使用坐标点时我都做不到。我需要以公里为单位的结果。

我试试:

SELECT ST_Distance('POINT(0.0 0.0)', ST_GeomFromText(location.coordenate)) FROM app.location as location;

要获得 metres/kilometres 中的距离,您需要将坐标转换为以米为单位的 SRS,或者如果可能,使用 geography 而不是 geometry,因为 ST_Distance returns两个geography参数的距离,单位为米(1km=1000m),例如

SELECT 
  ST_Distance(ST_MakePoint(0.0,0.0)::geography, coordenate::geography)/1000 
FROM app.location;

正在将 geometry / text 转换为 geography

演示:db<>fiddle

CREATE TABLE location (gid int, coordenate geometry(point,4326));
INSERT INTO location VALUES
(1,'SRID=4326;POINT(10 10)'),(2,'SRID=4326;POINT(0.1 0.1)');

SELECT 
  gid, ST_AsText(coordenate),
  ST_Distance(ST_MakePoint(0.0,0.0)::geography, coordenate::geography)/1000  
FROM location
ORDER BY coordenate::geography <-> ST_MakePoint(0.0,0.0)::geography;

gid |   st_astext    |      ?column?      
-----+----------------+--------------------
   2 | POINT(0.1 0.1) | 15.690343289660001
   1 | POINT(10 10)   | 1565.1090992178902
(2 rows)

运算符<->表示距离,因此在ORDER BY子句上使用它可以按距离对结果集进行排序。

正在将 point 转换为 geography

数据类型 point 不是 PostGIS 数据类型,而是来自 PostgreSQL 的 geometric data type。为了使用 ST_Distance,您必须将点转换为几何或地理。

演示:db<>fiddle

CREATE TABLE location (gid int, coordenate point);
INSERT INTO location VALUES
(1,point(10,10)),(2,point(0.1,0.1));

SELECT *,
  ST_Distance(
    ST_MakePoint(0.0,0.0)::geography, 
    ST_MakePoint(coordenate[0],coordenate[1])::geography)/1000 
FROM location
ORDER BY ST_MakePoint(coordenate[0],coordenate[1])::geography <-> ST_MakePoint(0.0,0.0)::geography;

 gid | coordenate |      ?column?      
-----+------------+--------------------
   2 | (0.1,0.1)  | 15.690343289660001
   1 | (10,10)    | 1565.1090992178902
(2 rows)

延伸阅读: