侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

用PostgreSQL数据库做地理位置app应用

数据库  /  管理员 发布于 6年前   158

项目中用到了postgreSQL中的earthdistance()函数功能计算地球上两点之间的距离,中文的资料太少了,我找到了一篇 英文的、讲的很好的文章  ,特此翻译,希望能够帮助到以后用到earthdistance的同学。

做一个GEO应用从来都不是一件容易的事。但是用一些身边的开源项目就可以在几分钟内轻松解决这个问题。 PostgreSQL有许多特性。是我的首选,它能够把数据库平台提升到另一个层次。

一、两种可用的选择

当我们想用Postgres作为GEO函数使用时,我们通常有2中选择(据我所知):
PostGIS: 为postgreSQL提供了高级GEO函数功能。我用了它一段时间,但是它对于我的需求来说太笨重了。
Cube和Earthdistance: 这两个拓展为轻量级的Geo关系实体提供了简单、快速的实现方法。

二、为什么在数据库服务器端做计算

这是件非常明显的事。服务器存储了所有的数据,服务器拓展是用C/C++实现的,非常快。为数据表做索引也能加快计算速度。

三、使用我的选择--Cube and EarthDistance

作为开始,你应该先建一个数据库(我想你知道该怎么做),然后使它们能用我们的架构。 执行:
复制代码 代码如下:CREATE EXTENSION cube;
然后执行:
复制代码 代码如下:CREATE EXTENSION earthdistance;
上面的命令创建了大约40个函数,以后我们做数据查询的时候就可以用了。
在我们的例子中,我创建了名为events的表,字段有:id(serial), name(varchar 255), lat(double), lng(double)。(别忘了~~)

四、计算2个坐标之间的距离

计算2个坐标之间的距离,我们要用到 earthdistance(lltoearth($latlngcube), lltoearth($latlng_cube)) 这个函数。 earthdistance()函数接受2组坐标值,返回值一个以米为单位的的数值。

这能用于很多场景,比如根据某一位置找到离其最近的发生的新闻事件的列表。数据库的操作可能就像下面这样:
复制代码 代码如下:
SELECT events.id events.name, eaerthdiatance(lltoearth({currentuserlat}, {currentuserlng}), llto_earth(events.lat, events.lng))
as distancefromcurrentlocation FROM events
ORDER BY distancefromcurretnlocation ASC;
这将给我们一个很nice的新闻事件列表,按他们的离我们当前位置的距离由近到远排序。第一个是离我们最近的。

五、找到某个半径范围内的记录

Cube和Earthdiatance拓展提供的另一个伟大的函数是 earthbox(lltoearch($latlngcub), $radiusinmetres) 。 这个函数通过简单的比较就能到找到某个半径范围内的所有记录。它是靠返回2点之间的“大圆距离”实现的。

【译者注】大圆距离(Great circle disstance)指的是从球面的一点A出发到达球面上另一点B,所经过的最短路径的长度。一般说来,球面上任意两点A和B都可以与球心确定唯一的大圆,这个大圆被称为黎曼圆,而在大圆上连接这两点的较短的一条弧的长度就是大圆距离。如果想了解更多,请看wiki: 大圆距离

它能用于查询我们城市中所有的新闻事件:
复制代码 代码如下:SELECT events.id, events.name FROM events WHERE earthbox({currentuserlat}, {currentuserlng}, {radiusinmetres}) @> llto_earth(events.lat, events.lng);
这条查询语句仅仅会返回在radius_ in_ metres指定的半径范围内的记录,非常简单吧!

六、提高查询速度

你可能会发现上面的查询有不小的开销。以我的经验,最好对一些字段建立索引。 (下面这条语句假定你又events表, 同时events表有字段lat和lng)
CREATE INDEX ${nameofindex} on events USING gits(lltoearth(lat, lng));

七、数据类型

我的应用比较简单,所以我把经纬度(lat和lng)都设成了double类型。这使得我用Node.js开发起来更加快速,而不用再去自己定制针对GIST类型的解决方案。

八、就这些!

很神奇,对么?!?我们仅仅用常用的数据类型(double)就足以去用一些GEO函数创建基于地理位置的社交app

九、我使用的postgreSQL语句总结(使用实例):

复制代码 代码如下:/*
* postgreSQL之earthdistance学习笔记
* author: wusuopubupt
* date: 2013-03-31
*/

/*创建表*/
CREATE TABLE picture (
  id serial PRIMARY KEY ,
  p_uid char(12) NOT NULL,
  p_key char(23) NOT NULL,
  lat real not null,
  lng real NOT NULL,
  up int NOT NULL,
  down int NOT NULL,
  ip varchar(15) DEFAULT NULL,
  address varchar(256) DEFAULT NULL
);

/*插入记录*/
INSERT INTO picture(p_uid, p_key, lat, lng, up, down, ip, address)
VALUES('aaaabbbbcccc', '2014032008164023279.png', 40.043945, 116.413668, 0, 0, '', '');

/*插入记录*/
INSERT INTO picture(p_uid, p_key, lat, lng, up, down, ip, address)
VALUES('xxxxccccmmmm', '2014032008164023111.png', 40.067183, 116.415230, 0, 0, '', '');

/*选择记录*/
SELECT * FROM picture;

/*更新记录*/
UPDATE picture SET address='LiShuiqiao' WHERE id=1;
UPDATE picture SET address='TianTongyuan' WHERE id=2;

/*对经纬度列创建索引*/
CREATE INDEX ll_idx on picture USING gist(ll_to_earth(lat, lng));

/*根据半径(1000米)选择记录*/
SELECT * FROM picture where earth_box(ll_to_earth(40.059286,116.418773),1000) @> ll_to_earth(picture.lat, picture.lng);

/*选择距离当前用户的距离*/
SELECT picture.id, earth_distance(ll_to_earth(picture.lat, picture.lng), ll_to_earth(40.059286,116.418773))
AS dis FROM picture
ORDER BY dis ASC;

/*
 * 以下内容是网上的一篇教程
 * 地址:http://www.cse.iitb.ac.in/dbms/Data/Courses/CS631/PostgreSQL-Resources/postgresql-9.2.4/contrib/earthdistance/expected/earthdistance.out
 */
--
--  Test earthdistance extension
--
-- In this file we also do some testing of extension create/drop scenarios.
-- That's really exercising the core database's dependency logic, so ideally
-- we'd do it in the core regression tests, but we can't for lack of suitable
-- guaranteed-available extensions.  earthdistance is a good test case because
-- it has a dependency on the cube extension.
--
CREATE EXTENSION earthdistance;  -- fail, must install cube first
ERROR:  required extension "cube" is not installed
CREATE EXTENSION cube;
CREATE EXTENSION earthdistance;
--
-- The radius of the Earth we are using.
--
SELECT earth()::numeric(20,5);
     earth    
---------------
 6378168.00000
(1 row)

--
-- Convert straight line distances to great circle distances.把直线距离转成大圆距离
--
SELECT (pi()*earth())::numeric(20,5);
    numeric    
----------------
 20037605.73216
(1 row)

SELECT sec_to_gc(0)::numeric(20,5);
 sec_to_gc
-----------
   0.00000
(1 row)


--
-- Convert great circle distances to straight line distances.
--
SELECT gc_to_sec(0)::numeric(20,5);
 gc_to_sec
-----------
   0.00000
(1 row)

SELECT gc_to_sec(sec_to_gc(2*earth()))::numeric(20,5);
   gc_to_sec   
----------------
 12756336.00000
(1 row)


--
-- Set coordinates using latitude and longitude.
-- Extract each coordinate separately so we can round them.
--
SELECT cube_ll_coord(ll_to_earth(0,0),1)::numeric(20,5),
 cube_ll_coord(ll_to_earth(0,0),2)::numeric(20,5),
 cube_ll_coord(ll_to_earth(0,0),3)::numeric(20,5);
 cube_ll_coord | cube_ll_coord | cube_ll_coord
---------------+---------------+---------------
 6378168.00000 |       0.00000 |       0.00000
(1 row)

SELECT cube_ll_coord(ll_to_earth(360,360),1)::numeric(20,5),
 cube_ll_coord(ll_to_earth(360,360),2)::numeric(20,5),
 cube_ll_coord(ll_to_earth(360,360),3)::numeric(20,5);
 cube_ll_coord | cube_ll_coord | cube_ll_coord
---------------+---------------+---------------
 6378168.00000 |       0.00000 |       0.00000
(1 row)


--
-- Test getting the latitude of a location.
--
SELECT latitude(ll_to_earth(0,0))::numeric(20,10);
   latitude  
--------------
 0.0000000000
(1 row)

SELECT latitude(ll_to_earth(45,0))::numeric(20,10);
   latitude   
---------------
 45.0000000000
(1 row)

--
-- Test getting the longitude of a location.
--
SELECT longitude(ll_to_earth(0,0))::numeric(20,10);
  longitude  
--------------
 0.0000000000
(1 row)

SELECT longitude(ll_to_earth(45,0))::numeric(20,10);
  longitude  
--------------
 0.0000000000
(1 row)


--
-- For the distance tests the following is some real life data.
--
-- Chicago has a latitude of 41.8 and a longitude of 87.6.
-- Albuquerque has a latitude of 35.1 and a longitude of 106.7.
-- (Note that latitude and longitude are specified differently
-- in the cube based functions than for the point based functions.)
--
--
-- Test getting the distance between two points using earth_distance.
--
SELECT earth_distance(ll_to_earth(0,0),ll_to_earth(0,0))::numeric(20,5);
 earth_distance
----------------
        0.00000
(1 row)

SELECT earth_distance(ll_to_earth(0,0),ll_to_earth(0,180))::numeric(20,5);
 earth_distance
----------------
 20037605.73216
(1 row)

--
-- Test getting the distance between two points using geo_distance.
--
SELECT geo_distance('(0,0)'::point,'(0,0)'::point)::numeric(20,5);
 geo_distance
--------------
      0.00000
(1 row)

SELECT geo_distance('(0,0)'::point,'(180,0)'::point)::numeric(20,5);
 geo_distance
--------------
  12436.77274
(1 row)


--
-- Test getting the distance between two points using the <@> operator.
--
SELECT ('(0,0)'::point <@> '(0,0)'::point)::numeric(20,5);
 numeric
---------
 0.00000
(1 row)

SELECT ('(0,0)'::point <@> '(180,0)'::point)::numeric(20,5);
   numeric  
-------------
 12436.77274
(1 row)


--
-- Test for points that should be in bounding boxes.
--
SELECT earth_box(ll_to_earth(0,0),
       earth_distance(ll_to_earth(0,0),ll_to_earth(0,1))*1.00001) @>
       ll_to_earth(0,1);
 ?column?
----------
 t
(1 row)

SELECT earth_box(ll_to_earth(0,0),
       earth_distance(ll_to_earth(0,0),ll_to_earth(0,0.1))*1.00001) @>
       ll_to_earth(0,0.1);
 ?column?
----------
 t
(1 row)


--
-- Test for points that shouldn't be in bounding boxes. Note that we need
-- to make points way outside, since some points close may be in the box
-- but further away than the distance we are testing.
--
SELECT earth_box(ll_to_earth(0,0),
       earth_distance(ll_to_earth(0,0),ll_to_earth(0,1))*.57735) @>
       ll_to_earth(0,1);
 ?column?
----------
 f
(1 row)

SELECT earth_box(ll_to_earth(0,0),
       earth_distance(ll_to_earth(0,0),ll_to_earth(0,0.1))*.57735) @>
       ll_to_earth(0,0.1);
 ?column?
----------
 f
(1 row)


  • 上一条:
    15个postgresql数据库实用命令分享
    下一条:
    Postgre数据库Insert 、Query性能优化详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客