如何使用Postgis执行邻近搜索?


9

我下载了Geonames数据库(cities1000),并编写了一个小的Ruby程序,将其导入到我的表(geo_cities)中。然后,我添加了名为的地理列geog

然后,我使用以下命令将所有经纬度数字转换为geog列:

update public.geo_cities set geog = st_GeogFromText('SRID=4326;POINT(' || longitude || ' ' || latitude || ')');

事情看起来很好。现在我要做的是找到布拉格100英里范围内的所有城市。

所以我可以像这样获得布拉格:

select * from geo_cities where asciiname = 'Prague' and countrycode = 'CZ';

我仍在学习GIS和Postgres,所以有人可以通过简单查询来帮助我吗?

Answers:


13

首先,请确保您在“地理位置”列上有一个索引。它将加快空间搜索:

CREATE INDEX geo_cities_geog_idx ON geo_cities USING GIST geog;
VACUUM ANALYZE geo_cities(geog);

然后,您可以对自联接查询使用ST_DWithin(从英里到米的转换):

SELECT gc.*, ST_Distance(gc.geog, pt.geog)/1609.344 AS distance_miles
FROM geo_cities gc, geo_cities pt
WHERE pt.asciiname = 'Prague' and pt.countrycode = 'CZ'
  AND ST_DWithin(gc.geog, pt.geog, 160934.4)
ORDER BY ST_Distance(gc.geog, pt.geog);

如果您正在寻找一本好书,请查看Action中的PostGIS

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.