对于当前位置或者选定省市位置进行查询
接口实现
/*** 查询地址* @ApiTitle (查询地址)* @ApiSummary (查询地址)* @ApiMethod (POST)* @ApiRoute (/api/demo/address)* @ApiParams (name="dart", type="integer", required=true, description="省ID")* @ApiParams (name="address", type="string", required=true, description="地区名称")* @ApiReturnParams (name="code", type="integer", required=true, sample="0")* @ApiReturnParams (name="msg", type="string", required=true, sample="返回成功")* @ApiReturn ({'code':'1','msg':'返回成功'})*/public function address(){$id = $this->request->param('dart');$address = $this->request->param('address');// 高德地图API接口地址$url = "https://restapi.amap.com/v3/place/text"; //poi搜索// API Key$key = "你自己在高德地图开放平台申请的应用key";// 搜索关键字$keyword = urlencode("$address");// 请求地址拼接$requestUrl = $url . "?key=" . $key . "&keywords=" . $keyword;// 发送请求并获取结果$curl = curl_init($requestUrl);curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);$response = curl_exec($curl);curl_close($curl);// 解析JSON结果$result = json_decode($response, true);// 输出解析结果
// $res = $result['pois'];//查询出当前传递的省市ID所涵盖的经纬度$find = db('area')->where('id', $id)->find();$data = [];
// dump($result['pois']);exit();foreach ($result['pois'] as $k => $v) {$data[$k]['name'] = $v['name'];$data[$k]['address'] = $v['address'];$location = explode(',', $v['location']);$data[$k]['distance'] = (new Resource())::getDistance($find['lng'], $find['lat'], $location[0], $location[1], 2, 2);}// 使用 array_column 函数获取数组中某个字段的值$scores = array_column($data, 'distance');// 使用 array_multisort 对距离进行排序array_multisort($scores, SORT_ASC, $data);$this->success('获取成功', $data);}
其中用到的getDistance方法如下[精确计算]
/*** 计算两点地理坐标之间的距离* @param Decimal $longitude1 起点经度* @param Decimal $latitude1 起点纬度* @param Decimal $longitude2 终点经度* @param Decimal $latitude2 终点纬度* @param Int $unit 单位 1:米 2:千米* @param Int $decimal 精度 保留小数位数* @return Decimal*/public static function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=1, $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);}
结果如图所示: