| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace addons\service\library;
- use app\api\model\service\ProjectConfigure;
- class Map
- {
- protected $reqUrl = "https://restapi.amap.com/v3/direction/driving?";
- protected $locationUrl = "https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=";
- /**
- * 计算两地距离
- * @param $param
- * @return false|float
- */
- public static function countDistance($param)
- {
- $config = ProjectConfigure::where('state',1)->find();
- $params = http_build_query(['key'=>$config['gaodekey'],'origin'=>implode(',',$param['user']),'destination'=>implode(',',$param['skill'])]);
- $url = (new Map())->reqUrl.$params;
- $res = self::getUrl($url);
- $distance = ceil($res['route']['paths'][0]['distance']/1000);
- return $distance;
- }
- /**
- * 根据经纬度获取详细地址
- * @param $lng
- * @param $lat
- * @return false|mixed
- */
- public static function getLocation($lng,$lat)
- {
- $config = ProjectConfigure::getProjectConfig();
- $key = $config['gaodekey'];
- $location = $lng . "," . $lat;
- $url = (new Map())->locationUrl."{$location}&key={$key}&radius=1000&extensions=all";
-
- try {
- $re = self::getUrl($url);
-
- // 检查返回结果
- if (!$re || !isset($re['status']) || $re['status'] != 1) {
- // 记录错误日志(如果需要)
- // \think\facade\Log::error('高德地图API调用失败', ['url' => $url, 'response' => $re]);
- return false;
- }
-
- return $re;
- } catch (\Exception $e) {
- // 记录异常日志(如果需要)
- // \think\facade\Log::error('高德地图API异常', ['message' => $e->getMessage(), 'url' => $url]);
- return false;
- }
- }
- public static function getUrl($url) {
- //初始化
- $ch = curl_init();
- //设置选项,包括URL
- curl_setopt($ch, CURLOPT_URL,$url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_HEADER, 0);
-
- // 添加 SSL 配置解决 HTTPS 请求问题
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书验证
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 跳过主机验证
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 允许重定向
- curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时时间30秒
-
- // 添加 User-Agent
- curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
-
- //执行并获取HTML文档内容
- $output = curl_exec($ch);
-
- // 添加错误处理
- if (curl_errno($ch)) {
- $error = curl_error($ch);
- curl_close($ch);
- throw new \Exception("cURL Error: " . $error);
- }
-
- //释放curl句柄
- curl_close($ch);
- //打印获得的数据
- return json_decode($output,true);
- }
- }
|