【问题标题】:Nearest places from a certain point从某个点最近的地方
【发布时间】:2012-09-20 15:10:47
【问题描述】:

我有下表

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

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

查询所有接近特定纬度/经度的地方应该是什么?

gis 已安装。

【问题讨论】:

    标签: postgresql postgis postgresql-9.1


    【解决方案1】:

    如果你真的想使用 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 接受几何并且 ST_MakePoint 已经返回几何。那么那里到底发生了什么!?
    • 几何类型上的 ST_Distance 使用笛卡尔距离,如果使用度 lng/lat 的距离单位会产生误导。地理类型上的 ST_Distance 查找 WGS 84 椭球体周围的最小距离,并返回以米为单位的实际距离。
    • 啊。对的,我刚刚跳过了。谢谢。 :)
    【解决方案2】:
    select *
    from places
    where lat_lng <-> POINT(-125.4, 46.32) < 1
    order by lat_lng <-> POINT(-125.4, 46.32)
    

    【讨论】:

    • 感谢您的回答。这是工作。你能告诉我,&lt; 1 在这个查询中有什么用处。
    【解决方案3】:

    在位置字段上创建索引:

    CREATE INDEX ON table_name USING GIST(location);
    

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2014-03-16
      • 2023-03-11
      • 2012-03-10
      • 1970-01-01
      相关资源
      最近更新 更多