今天在使用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)
结果果真符合预期!
本文介绍了在PostgreSQL中利用PostGIS扩展如何根据经纬度正确计算两点间的距离,并解决将距离误算为度数的问题。通过ST_Distance函数确保计算的是以米为单位的测地线距离。
3899

被折叠的 条评论
为什么被折叠?



