今天在使用PostgreSQL的PostGIS功能来实现根据经纬度计算距离和计算某一经纬度附近X米之内的地点,发现了一些错误,实现SQL语句和更正的语句如下

计算两经纬度之间距离:

select ST_Distance(ST_GeomFromEWKT('SRID=4326;POINT(lng1 lat1)'),ST_SetSRID(ST_Point(lng2::double precision, lat2::double precision), 4326))

计算(lng2, lat2)是否在(lng1, lat1)的X米之内

select ST_DWithin(ST_SetSRID(ST_Point(lng1::double precision, lat1::double precision), 4326),ST_GeomFromEWKT('SRID=4326;POINT(lng2 lat2)'), X)

例子:

(116.45815259398,39.938559769396):北京三里屯CHAO
(117.26089170529,40.644852995474):古北水镇
(117.26608,40.647293):北京好梦居民宿

结果却大大的超出了我的预料,距离算出来的是相差度数,附近的点直接将X米当作度数处理

于是我就点开了ST_Distance函数

create function st_distance(geography, geography) returns double precision
    immutable
    strict
    parallel safe
    language sql
as
$$
SELECT public._ST_Distance($1, $2, 0.0, true)
$$;

comment on function st_distance(geography, geography) is 'args: gg1, gg2 - For geometry type Returns the 2D Cartesian distance between two geometries in projected units (based on spatial ref). For geography type defaults to return minimum geodesic distance between two geographies in meters.';

alter function st_distance(geography, geography) owner to postgres;

原来注释写的很是清楚:For geography type defaults to return minimum geodesic distance between two geographies in meters(对于geography类型,默认返回两个地理位置之间的最小测地距离(以米为单位))

计算两经纬度之间距离:

select ST_Distance(ST_GeomFromEWKT('SRID=4326;POINT(lng1 lat1)') :: geography,ST_SetSRID(ST_Point(lng2::double precision, lat2::double precision), 4326) :: geography)

计算(lng2, lat2)是否在(lng1, lat1)的X米之内

select ST_DWithin(ST_SetSRID(ST_Point(lng1::double precision, lat1::double precision), 4326) :: geography,ST_GeomFromEWKT('SRID=4326;POINT(lng2 lat2)') :: geography, X)

结果果真符合预期!

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐