计算1千米内最大最小的经纬度&&计算地球上两点之间距离python

在开发一起玩耍app的时候,有一些距离的处理,整理出这个

  1. 计算x千米范围内的最大最小经纬度,用来从数据库中检索数据

php方法:

$myLat = $postObj->Location_X;//接收到的当前位置的纬度
$myLng = $postObj->Location_Y;//接收到的当前位置的经度

$Label = $postObj->Label;//接收到的当前地理位置信息
$Label = iconv("UTF-8","GBK",$Label);
$find = stripos($Label,' ');//过滤掉邮政编码 纯属为了整洁性
if($find!==false)
{
    $Label = substr($Label,0,$find);
}

//以下为核心代码
$range = 180 / pi() * 1 / 6372.797;     //里面的 1 就代表搜索 1km 之内,单位km
$lngR = $range / cos($myLat * pi() / 180);
$maxLat = $myLat + $range;//最大纬度
$minLat = $myLat - $range;//最小纬度
$maxLng = $myLng + $lngR;//最大经度
$minLng = $myLng - $lngR;//最小经度
//得出这四个值以后,就可以根据你数据库里存的经纬度信息查找记录了~

python方法:

import math
# 计算x千米范围内的的最大最小经纬度
def calcu_location(location_x, location_y, r=1):
    lat_range = 180 / math.pi * r / 6372.797  # 里面的 1 就代表搜索 1km 之内,单位km
    long_r = lat_range / math.cos(location_x * math.pi / 180)
    max_lat = location_x + lat_range  # 最大纬度
    min_lat = location_x - lat_range  # 最小纬度
    max_long = location_y + long_r  # 最大经度
    min_long = location_y - long_r  # 最小经度
    
    range_xy = {}
    range_xy['location_x'] = {'min':min_lat, 'max':max_lat}
    range_xy['location_y'] = {'min':min_long, 'max':max_long}
    return range_xy

测试:

print calcu_location(-30.376393,-114.33879)

输出:

{'location_x': {'max': -30.367402319846047, 'min': -30.385383680153954}, 'location_y': {'max': -114.32836870647137, 'min': -114.34921129352864}}


2.  计算地球上两点之间距离,单位千米

python方法:

#计算两点距离,输入两点经纬度,输出距离:千米
def rad(flo):
    return flo * math.pi / 180.0
    
def calcu_distance(lat1,lng1,lat2,lng2):
    earth_radius=6378.137
    radlat1=rad(lat1)
    radlat2=rad(lat2)
    a=radlat1-radlat2
    b=rad(lng1)-rad(lng2)
    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
    if s<0:
        return round(-s,2)
    else:
        return round(s,2)


转载于:https://my.oschina.net/freegeek/blog/221341

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值