从某个点开始,距离最近的地方

9

我有以下表格

create table places(lat_lng point, place_name varchar(50));

insert into places values (POINT(-126.4, 45.32), 'Food Bar');

如何查询距离特定经纬度附近的所有位置?

已安装gis。

3个回答

10

如果你确实想使用PostGIS:

create table places(
    lat_lng geography(Point,4326),
    place_name varchar(50)
);

-- Two ways to make a geography point
insert into places values (ST_MakePoint(-126.4, 45.32), 'Food Bar1');
insert into places values ('POINT(-126.4 45.32)', 'Food Bar2');

-- Spatial index
create index places_lat_lng_idx on places using gist(lat_lng);

现在要查找1公里(或1000米)内的所有位置:

select *, ST_Distance(lat_lng, ST_MakePoint(-126.4, 45.32)::geography)
from places
where ST_DWithin(lat_lng, ST_MakePoint(-126.4, 45.32)::geography, 1000)
order by ST_Distance(lat_lng, ST_MakePoint(-126.4, 45.32)::geography);

你知道为什么我们必须将 ST_MakePoint 强制转换为 geography 吗?我遇到了一个问题,当我没有进行类型转换时,ST_Distance 返回了错误的结果。ST_distance 接受 geometry 类型,而 ST_MakePoint 已经返回了 geometry 类型。那么到底发生了什么事情呢? - Bibhas Debnath
ST_Distance函数用于计算几何类型之间的距离,它使用笛卡尔距离。但如果使用经度/纬度作为距离单位,则会产生误导。对于地理类型,ST_Distance函数会在WGS 84椭球体周围找到最小距离,并以米为单位返回真实距离。 - Mike T
啊,对了,我刚才跳过了。谢谢。 :) - Bibhas Debnath

9
select *
from places
where lat_lng <-> POINT(-125.4, 46.32) < 1
order by lat_lng <-> POINT(-125.4, 46.32)

谢谢你的回答。它有效了。请问在这个查询中,"<1" 的用途是什么? - Irshad Khan

0
在一个位置字段上创建索引:
CREATE INDEX ON table_name USING GIST(location);

GiST索引能够优化“最近邻”搜索:

SELECT * FROM table_name ORDER BY location <-> point '(-74.013, 40.711)' LIMIT 10;

注意:点的第一个元素是经度,第二个元素是纬度。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接