根据地址获取经纬度以及计算两个经纬度之间的距离
程序员文章站
2024-02-14 22:59:04
...
/**
* 获取经纬度
* $keyword:地址详情
*/
function get_location($keyword){
$header[] = 'Referer: http://lbs.qq.com/webservice_v1/guide-suggestion.html';
$header[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36';
$url = "http://apis.map.qq.com/ws/place/v1/suggestion/?®ion=&key=3RCBZ-WY66F-XSMJ3-NXBO3-MH7LT-FSBRX&keyword=".$keyword;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
//执行并获取HTML文档内容
$output = curl_exec($ch);
//释放curl句柄
curl_close($ch);
// return $output;
$result = json_decode($output,true);
if(!empty($result['data'])){
$res = $result['data'][0];
}else{
$res = '';
}
// print_r($result);
return $res;
}
计算两个经纬度之间的距离
/**
* 计算两点地理坐标之间的距离
* @param Decimal $longitude1 起点经度
* @param Decimal $latitude1 起点纬度
* @param Decimal $longitude2 终点经度
* @param Decimal $latitude2 终点纬度
* @param Int $unit 单位 1:米 2:公里
* @param Int $decimal 精度 保留小数位数
* @return Decimal
*/
function get_distance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){
$EARTH_RADIUS = 6370.996; // 地球半径系数
$PI = 3.1415926;
$radLat1 = $latitude1 * $PI / 180.0;
$radLat2 = $latitude2 * $PI / 180.0;
$radLng1 = $longitude1 * $PI / 180.0;
$radLng2 = $longitude2 * $PI /180.0;
$a = $radLat1 - $radLat2;
$b = $radLng1 - $radLng2;
$distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
$distance = $distance * $EARTH_RADIUS * 1000;
if($unit==2){
$distance = $distance / 1000;
}
return round($distance, $decimal);
}
获取符合条件的店铺列表:
/**
* 附近8km的店铺
*/
public function place(){
$lat = $this->request->post('lat'); //当前维度
$lng = $this->request->post('lng');//当前经度
$t = date('H:i:s');
$where = [
['status', '=', 1],
['level', '<>', 0],
['open_time', '<=', $t],
['close_time', '>=', $t],
];
$list = admin::where($where)->select()->toArray(); //所有店铺列表
$arr = [];
foreach ($list as $k => &$v){
$distance = get_distance($lng,$lat,$v['longitude'],$v['latitude']);
$v['distance'] = $distance;
if($distance >8){
continue;
}
array_push($arr,$v);
}
if(empty($arr)){
$sort = [
'direction' => 'SORT_ASC', //排序顺序标志 SORT_DESC 降序;SORT_ASC 升序
'field' => 'distance', //排序字段
];
$arrSort = [];
foreach($arr AS $uniqid => $row){
foreach($row AS $key=>$value){
$arrSort[$key][$uniqid] = $value;
}
}
if($sort['direction']){
array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arr);
}
$this->success('admin店铺',$list);
}
$this->success('访问成功',$arr);
}
上一篇: 判断经纬度是否在某个区域内