在开发一起玩耍app的时候,有一些距离的处理,整理出这个
计算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)