SQL SERVER 根据地图经纬度计算距离函数

前些天客户提出一个这样的要求:一个手机订餐网,查询当前所在位置的5公里范围的酒店,然后客户好去吃饭。
拿到这个请求后,不知道如何下手,静静地想了一下,在酒店的表中增加两个字段,用来存储酒店所在的经度和纬度,当订餐的时候,要求手机得到当前客户所在的经度和纬度传过来,再与数据库中酒店的经度和纬度计算一下,就查出来。

为了在数据库中查询两点之间的距离,所以这个函数需要在数据库中定义。

我网上找了很久,却没有找到这个函数。最后在CSDN上,一个朋友的帮助下解决了这个问题,非常感谢lordbaby给我提供这个函数,我把这个函数放到这里来,以便帮助更多许要的朋友。

 

[sql] view plain copy
 
 print?在CODE上查看代码片派生到我的代码片
  1. --计算地球上两个坐标点(经度,纬度)之间距离sql函数  
  2. --作者:lordbaby  
  3. --整理:www.aspbc.com   
  4. CREATE FUNCTION [dbo].[fnGetDistance](@LatBegin REAL, @LngBegin REAL, @LatEnd REAL, @LngEnd REAL) RETURNS FLOAT  
  5.   AS  
  6. BEGIN  
  7.   --距离(千米)  
  8.   DECLARE @Distance REAL  
  9.   DECLARE @EARTH_RADIUS REAL  
  10.   SET @EARTH_RADIUS = 6378.137    
  11.   DECLARE @RadLatBegin REAL,@RadLatEnd REAL,@RadLatDiff REAL,@RadLngDiff REAL  
  12.   SET @RadLatBegin = @LatBegin *PI()/180.0    
  13.   SET @RadLatEnd = @LatEnd *PI()/180.0    
  14.   SET @RadLatDiff = @RadLatBegin - @RadLatEnd    
  15.   SET @RadLngDiff = @LngBegin *PI()/180.0 - @LngEnd *PI()/180.0     
  16.   SET @Distance = 2 *ASIN(SQRT(POWER(SIN(@RadLatDiff/2), 2)+COS(@RadLatBegin)*COS(@RadLatEnd)*POWER(SIN(@RadLngDiff/2), 2)))  
  17.   SET @Distance = @Distance * @EARTH_RADIUS    
  18.   --SET @Distance = Round(@Distance * 10000) / 10000    
  19.   RETURN @Distance  
  20. END  

 

[sql] view plain copy
 
 print?在CODE上查看代码片派生到我的代码片
  1. --经度 Longitude 简写Lng,  纬度 Latitude 简写Lat  
  2. --跟坐标距离小于5公里的数据  
  3. SELECT * FROM 商家表名 WHERE dbo.fnGetDistance(121.4625,31.220937,longitude,latitude) < 5  

 

这里的longitude,latitude分别是酒店的经度和纬度字段,而121.4625,31.220937是手机得到的当前客户所在的经度,后面的5表示5公里范围之内。

JS版本

 

[javascript] view plain copy
 
 print?在CODE上查看代码片派生到我的代码片
    1. function toRadians(degree) {  
    2.     return degree * Math.PI / 180;  
    3. }  
    4. function distance(latitude1, longitude1, latitude2, longitude2) {  
    5.     // R is the radius of the earth in kilometers  
    6.     var R = 6371;  
    7.     var deltaLatitude = toRadians(latitude2-latitude1);  
    8.     var deltaLongitude = toRadians(longitude2-longitude1);  
    9.     latitude1 =toRadians(latitude1);  
    10.     latitude2 =toRadians(latitude2);  
    11.     var a = Math.sin(deltaLatitude/2) *  
    12.     Math.sin(deltaLatitude/2) +  
    13.     Math.cos(latitude1) *  
    14.     Math.cos(latitude2) *  
    15.     Math.sin(deltaLongitude/2) *  
    16.     Math.sin(deltaLongitude/2);  
    17.     var c = 2 * Math.atan2(Math.sqrt(a),  
    18.     Math.sqrt(1-a));  
    19.     var d = R * c;  
    20.     return d;  
    21. }  
posted @ 2016-12-02 09:58  尐Scorpios  阅读(290)  评论(0编辑  收藏  举报