Map.php 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace addons\service\library;
  3. use app\api\model\service\ProjectConfigure;
  4. class Map
  5. {
  6. protected $reqUrl = "https://restapi.amap.com/v3/direction/driving?";
  7. protected $locationUrl = "https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=";
  8. /**
  9. * 计算两地距离
  10. * @param $param
  11. * @return false|float
  12. */
  13. public static function countDistance($param)
  14. {
  15. $config = ProjectConfigure::where('state',1)->find();
  16. $params = http_build_query(['key'=>$config['gaodekey'],'origin'=>implode(',',$param['user']),'destination'=>implode(',',$param['skill'])]);
  17. $url = (new Map())->reqUrl.$params;
  18. $res = self::getUrl($url);
  19. $distance = ceil($res['route']['paths'][0]['distance']/1000);
  20. return $distance;
  21. }
  22. /**
  23. * 根据经纬度获取详细地址
  24. * @param $lng
  25. * @param $lat
  26. * @return false|mixed
  27. */
  28. public static function getLocation($lng,$lat)
  29. {
  30. $config = ProjectConfigure::getProjectConfig();
  31. $key = $config['gaodekey'];
  32. $location = $lng . "," . $lat;
  33. $url = (new Map())->locationUrl."{$location}&key={$key}&radius=1000&extensions=all";
  34. try {
  35. $re = self::getUrl($url);
  36. // 检查返回结果
  37. if (!$re || !isset($re['status']) || $re['status'] != 1) {
  38. // 记录错误日志(如果需要)
  39. // \think\facade\Log::error('高德地图API调用失败', ['url' => $url, 'response' => $re]);
  40. return false;
  41. }
  42. return $re;
  43. } catch (\Exception $e) {
  44. // 记录异常日志(如果需要)
  45. // \think\facade\Log::error('高德地图API异常', ['message' => $e->getMessage(), 'url' => $url]);
  46. return false;
  47. }
  48. }
  49. public static function getUrl($url) {
  50. //初始化
  51. $ch = curl_init();
  52. //设置选项,包括URL
  53. curl_setopt($ch, CURLOPT_URL,$url);
  54. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  55. curl_setopt($ch, CURLOPT_HEADER, 0);
  56. // 添加 SSL 配置解决 HTTPS 请求问题
  57. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书验证
  58. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 跳过主机验证
  59. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 允许重定向
  60. curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时时间30秒
  61. // 添加 User-Agent
  62. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
  63. //执行并获取HTML文档内容
  64. $output = curl_exec($ch);
  65. // 添加错误处理
  66. if (curl_errno($ch)) {
  67. $error = curl_error($ch);
  68. curl_close($ch);
  69. throw new \Exception("cURL Error: " . $error);
  70. }
  71. //释放curl句柄
  72. curl_close($ch);
  73. //打印获得的数据
  74. return json_decode($output,true);
  75. }
  76. }