ApiBaseController.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /**
  3. * @Created by PhpStorm
  4. * @author: Kirin
  5. * @day: 2024/11/20
  6. * @time: 11:24
  7. */
  8. namespace app\common;
  9. use app\Request;
  10. use Joypack\Tencent\Map\Bundle\Location;
  11. use Joypack\Tencent\Map\Bundle\LocationOption;
  12. use qiniu\basic\BaseController;
  13. abstract class ApiBaseController extends BaseController
  14. {
  15. /**
  16. * 当前登陆用户信息
  17. * @var
  18. */
  19. protected $userInfo;
  20. /**
  21. * 当前登陆用户ID
  22. * @var
  23. */
  24. protected $uid;
  25. protected $service = null;
  26. /**
  27. * 初始化
  28. */
  29. public function __construct(Request $request)
  30. {
  31. parent::__construct($request);
  32. $this->initialize();
  33. }
  34. protected function initialize()
  35. {
  36. $this->uid = $this->request->uid();
  37. $this->userInfo = $this->request->user();
  38. }
  39. /**
  40. * @return array
  41. */
  42. public function getAddress(): array
  43. {
  44. list($latitude, $longitude) = $this->request->location();
  45. $address = $this->geoLbscoder($latitude, $longitude);
  46. if ($address) {
  47. return [
  48. 'address' => $address['address_component'],
  49. 'formatted_addresses' => $address['formatted_addresses'],
  50. 'info' => $address['ad_info'],
  51. ];
  52. }
  53. return [];
  54. }
  55. /**
  56. * 经纬度反向解析地址
  57. * @param string $latitude
  58. * @param string $longitude
  59. * @return mixed|null
  60. */
  61. private function geoLbscoder(string $latitude, string $longitude)
  62. {
  63. if (!$latitude || !$longitude) {
  64. return null;
  65. }
  66. $mapKey = sys_config('tengxun_map_key');
  67. $mapKSecret = sys_config('tengxun_map_secret', '');
  68. if (!$mapKSecret) $mapKSecret = null;
  69. if (!$mapKey) {
  70. return null;
  71. }
  72. try {
  73. $locationOption = new LocationOption($mapKey, $mapKSecret);
  74. $locationOption->setLocation($latitude, $longitude);
  75. $location = new Location($locationOption);
  76. $res = $location->request();
  77. if ($res->error) {
  78. return null;
  79. }
  80. if ($res->status) {
  81. return null;
  82. }
  83. if (!$res->result) {
  84. return null;
  85. }
  86. return $res->result;
  87. } catch (\Throwable $e) {
  88. return null;
  89. }
  90. }
  91. }