算法_经纬度算距离

项目里面用到的,需要算两个人之间的距离,用了两种算法,

参考这里:http://www.cnblogs.com/ouling/archive/2011/08/26/2154555.html

因为是用在服务器端的,我用python写的,大家可以看一下

实验证明第二种方法是对的:


#input degrees not radians
import math
'''
laA = 30.509909
lonA = 114.406478
laB = 30.509
lonB = 114.406
'''
laA, lonA = (30.505336, 114.393532)
laB, lonB = (30.506760, 114.395807)
'''
Rely on Google map calcution:

   double radLat1 = rad(lat1);
   double radLat2 = rad(lat2);
   double a = radLat1 - radLat2;
   double b = rad(lng1) - rad(lng2);
   double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a/2),2) + 
    Math.Cos(radLat1)*Math.Cos(radLat2)*Math.Pow(Math.Sin(b/2),2)));
   s = s * EARTH_RADIUS;
   s = Math.Round(s * 10000) / 10000;
   return s;
'''
'''
calclute the distance between two point
'''
def calcDist(laA, lonA, laB, lonB):
    '''
    trans args form degrees to radians
    '''
    R = 6371000
    laA = math.radians(laA)
    laB = math.radians(laB)
    lonA = math.radians(lonA)
    lonB = math.radians(lonB)
    d1 = math.sin(laA) * math.sin(laB)
    d2 = math.cos(laA) * math.cos(laB) * math.cos(laA - laB)
    dist = R * math.acos(d1 + d2) * math.pi / 180
    return dist

def calcDistGoogle(laA, lonA, laB, lonB):
    R = 6341000
    laA = math.radians(laA)
    laB = math.radians(laB)
    lonA = math.radians(lonA)
    lonB = math.radians(lonB)
    a = laA - laB
    b = lonA - lonB
    s = 2 * math.asin(math.sqrt(
                                math.pow(math.sin(a/2),2)
                                + math.cos(laA) * math.cos(laB) *math.pow(math.sin(b/2), 2)
                                ))
    s = s * R
    return s
print calcDist(laA, lonA, laB, lonB)
print calcDistGoogle(laA, lonA, laB, lonB)










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值