地理坐标计算

/*根据半径(1000米)选择记录 */
SELECT * FROM pointlocation where earth_box(ll_to_earth(40.057031,116.307852),4000) @> ll_to_earth(pointlocation.lat, pointlocation.lon);

/*判两点间的距离*/
SELECT earth_distance(ll_to_earth(40.057031,116.307852), ll_to_earth(pointlocation.lat, pointlocation.lon)) FROM pointlocation where id=1112

 /*矩形范围查找*/

SELECT *
from pointlocation
where
ST_Contains(ST_MakePolygon(ST_GeomFromText('LINESTRING ( 116.845397 40.008134 , 116.221114 40.008134 ,116.245397 40.108134 , 116.245397 41.108134 , 116.845397 40.008134) ')) ,st_point(pointlocation.lon,pointlocation.lat))='t'

  1. /*  
  2. * postgreSQL之earthdistance学习笔记  
  3. * author: wusuopubupt  
  4. date: 2013-03-31  
  5. */  
  6.   
  7. /*创建表*/  
  8. CREATE TABLE picture (  
  9.   id serial PRIMARY KEY ,  
  10.   p_uid char(12) NOT NULL,  
  11.   p_key char(23) NOT NULL,  
  12.   lat real not null,  
  13.   lng real NOT NULL,  
  14.   up int NOT NULL,  
  15.   down int NOT NULL,  
  16.   ip varchar(15) DEFAULT NULL,  
  17.   address varchar(256) DEFAULT NULL  
  18. );  
  19.   
  20. /*插入记录*/  
  21. INSERT INTO picture(p_uid, p_key, lat, lng, up, down, ip, address)   
  22. VALUES('aaaabbbbcccc', '2014032008164023279.png', 40.043945, 116.413668, 0, 0, '', '');  
  23.   
  24. /*插入记录*/  
  25. INSERT INTO picture(p_uid, p_key, lat, lng, up, down, ip, address)   
  26. VALUES('xxxxccccmmmm', '2014032008164023111.png', 40.067183, 116.415230, 0, 0, '', '');  
  27.   
  28. /*选择记录*/  
  29. SELECT * FROM picture;  
  30.   
  31. /*更新记录*/  
  32. UPDATE picture SET address='LiShuiqiao' WHERE id=1;  
  33. UPDATE picture SET address='TianTongyuan' WHERE id=2;  
  34.   
  35. /*对经纬度列创建索引*/  
  36. CREATE INDEX ll_idx on picture USING gist(ll_to_earth(lat, lng));  
  37.   
  38. /*根据半径(1000米)选择记录*/  
  39. SELECT * FROM picture where earth_box(ll_to_earth(40.059286,116.418773),1000) @> ll_to_earth(picture.lat, picture.lng);   
  40.   
  41. /*选择距离当前用户的距离*/  
  42. SELECT picture.id, earth_distance(ll_to_earth(picture.lat, picture.lng), ll_to_earth(40.059286,116.418773))   
  43. AS dis FROM picture   
  44. ORDER BY dis ASC;  
  45.   
  46. /*  
  47.  * 以下内容是网上的一篇教程  
  48.  * 地址:http://www.cse.iitb.ac.in/dbms/Data/Courses/CS631/PostgreSQL-Resources/postgresql-9.2.4/contrib/earthdistance/expected/earthdistance.out  
  49.  */  
原文地址:https://www.cnblogs.com/viewcozy/p/4795018.html