AddressGeo.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. namespace app\utils;
  3. class AddressGeo
  4. {
  5. // 阿里云使用地理编码-百度版
  6. // 文档 https://market.aliyun.com/apimarket/detail/cmapi00067007
  7. // 测试code: 505645dec3e747e3b294acbf5053c3a4 Todo 删掉
  8. public static function AliCloud($address, $appcode)
  9. {
  10. try {
  11. if (empty($address) || empty($appcode)) {
  12. throw new \Exception('Error: address or appcode is empty');
  13. }
  14. $api = 'https://lhjwddzzh.market.alicloudapi.com/geocode/baidu/geo/query';
  15. $res = http_post($api, [
  16. 'body' => http_build_query([
  17. 'address' => $address,
  18. ]),
  19. 'headers' => [
  20. 'Content-Type' => 'application/x-www-form-urlencoded',
  21. 'Authorization' => 'APPCODE ' . $appcode,
  22. ],
  23. ]);
  24. if ($res->getStatusCode() != 200) {
  25. throw new \Exception('Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
  26. }
  27. $data = json_decode((string)$res->getBody(), true);
  28. if ($data['code'] == 200) {
  29. return [
  30. 'lng' => $data['data']['location']['lng'],
  31. 'lat' => $data['data']['location']['lat'],
  32. ];
  33. }
  34. throw new \Exception('Error: ' . $data['code'] . ' ' . $data['msg']);
  35. } catch (\Throwable $e) {
  36. return [
  37. 'lng' => 0,
  38. 'lat' => 0,
  39. ];
  40. }
  41. }
  42. }