SQL SERVER 根据地图经纬度计算距离函数
前些天客户提出一个这样的要求:一个手机订餐网,查询当前所在位置的5公里范围的酒店,然后客户好去吃饭。
拿到这个请求后,不知道如何下手,静静地想了一下,在酒店的表中增加两个字段,用来存储酒店所在的经度和纬度,当订餐的时候,要求手机得到当前客户所在的经度和纬度传过来,再与数据库中酒店的经度和纬度计算一下,就查出来。
为了在数据库中查询两点之间的距离,所以这个函数需要在数据库中定义。
我网上找了很久,却没有找到这个函数。最后在CSDN上,一个朋友的帮助下解决了这个问题,非常感谢lordbaby给我提供这个函数,我把这个函数放到这里来,以便帮助更多许要的朋友。
- --计算地球上两个坐标点(经度,纬度)之间距离sql函数
- --作者:lordbaby
- --整理:www.aspbc.com
- CREATE FUNCTION [dbo].[fnGetDistance](@LatBegin REAL, @LngBegin REAL, @LatEnd REAL, @LngEnd REAL) RETURNS FLOAT
- AS
- BEGIN
- --距离(千米)
- DECLARE @Distance REAL
- DECLARE @EARTH_RADIUS REAL
- SET @EARTH_RADIUS = 6378.137
- DECLARE @RadLatBegin REAL,@RadLatEnd REAL,@RadLatDiff REAL,@RadLngDiff REAL
- SET @RadLatBegin = @LatBegin *PI()/180.0
- SET @RadLatEnd = @LatEnd *PI()/180.0
- SET @RadLatDiff = @RadLatBegin - @RadLatEnd
- SET @RadLngDiff = @LngBegin *PI()/180.0 - @LngEnd *PI()/180.0
- SET @Distance = 2 *ASIN(SQRT(POWER(SIN(@RadLatDiff/2), 2)+COS(@RadLatBegin)*COS(@RadLatEnd)*POWER(SIN(@RadLngDiff/2), 2)))
- SET @Distance = @Distance * @EARTH_RADIUS
- --SET @Distance = Round(@Distance * 10000) / 10000
- RETURN @Distance
- END
- --经度 Longitude 简写Lng, 纬度 Latitude 简写Lat
- --跟坐标距离小于5公里的数据
- SELECT * FROM 商家表名 WHERE dbo.fnGetDistance(121.4625,31.220937,longitude,latitude) < 5
这里的longitude,latitude分别是酒店的经度和纬度字段,而121.4625,31.220937是手机得到的当前客户所在的经度,后面的5表示5公里范围之内。
JS版本
- function toRadians(degree) {
- return degree * Math.PI / 180;
- }
- function distance(latitude1, longitude1, latitude2, longitude2) {
- // R is the radius of the earth in kilometers
- var R = 6371;
- var deltaLatitude = toRadians(latitude2-latitude1);
- var deltaLongitude = toRadians(longitude2-longitude1);
- latitude1 =toRadians(latitude1);
- latitude2 =toRadians(latitude2);
- var a = Math.sin(deltaLatitude/2) *
- Math.sin(deltaLatitude/2) +
- Math.cos(latitude1) *
- Math.cos(latitude2) *
- Math.sin(deltaLongitude/2) *
- Math.sin(deltaLongitude/2);
- var c = 2 * Math.atan2(Math.sqrt(a),
- Math.sqrt(1-a));
- var d = R * c;
- return d;
- }
网站网址:lscfan.com