sql - Postgres - 使用 postgis 计算距离
问题描述
在寻找了几天之后,尝试了我找到的所有内容,我在这里询问如何使用 PostGis 计算 Postgres 上两点之间的距离。我有一张叫做位置的桌子。该表有一个类型为点的“坐标”列。当用户在应用程序上插入一个值时,我需要获取按近距离排序的位置。我知道我需要使用 ST_Distance,但每次我尝试投射坐标点时我都不能。我需要以公里为单位的结果。
我尝试:
SELECT ST_Distance('POINT(0.0 0.0)', ST_GeomFromText(location.coordenate)) FROM app.location as location;
解决方案
要获得以米/公里为单位的距离,您需要将坐标转换为以米为单位的 SRS,或者如果可能,使用geography
代替geometry
,以ST_Distance
返回以米为单位的两个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 数据类型,而是来自geometric data type
PostgreSQL。为了使用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)
进一步阅读:
推荐阅读
- r - R中的barplot():标记,大小,标签
- unit-testing - 使用 Mockk 进行单元测试,java.lang.ClassCastException:PhoneValidationKt$isPhoneValid$1 无法转换为 kotlin.jvm.functions.Function1
- microsoft-graph-api - 在 365 群组上设置群组设置
- android - 如何将逻辑移动到 ViewModel?
- monitoring - 监控自指标更改以来的秒数作为普罗米修斯时间序列
- html - Flask:如何使用从数据库中获取的值作为函数的输入
- reactjs - 类型“{}”.ts(2339) 上不存在属性“详细信息”
- openssl - 在什么情况下,您会将 openssl ca 的 `unique_subject` 设置为 yes?
- python-3.x - tkinter TclError:小部件属性上的未知选项
- typescript - 如何在 TypeScript 中克隆类实例?