mapUtil.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. /**
  3. * User: ssh
  4. * Date: 2019/11/20
  5. * Time: 23:21
  6. */
  7. namespace common\components;
  8. use linslin\yii2\curl;
  9. use yii\helpers\Json;
  10. class mapUtil
  11. {
  12. public static $thirdMapKey = 'd4ab169335937fb56581ba15ea1bd1a1';
  13. public static function suggestion($region, $keyword)
  14. {
  15. if (getenv('YII_ENV') == 'production') {
  16. $url = "https://restapi.amap.com/v3/assistant/inputtips?city={$region}&keywords={$keyword}&key=" . self::$thirdMapKey;
  17. } else {
  18. $url = "http://restapi.amap.com/v3/assistant/inputtips?city={$region}&keywords={$keyword}&key=" . self::$thirdMapKey;
  19. }
  20. $curl = new curl\Curl();
  21. $result = $curl->get($url);
  22. return Json::decode($result);
  23. }
  24. //计算距离 lng经度 lat纬度 ssh 2020.5.14
  25. public static function calculateDistance($fromLnt, $fromLat, $toLnt, $toLat)
  26. {
  27. if (getenv('YII_ENV') == 'production') {
  28. $url = "https://restapi.amap.com/v5/direction/electrobike?key=" . self::$thirdMapKey . '&origin=' . $fromLnt . ',' . $fromLat . '&destination=' . $toLnt . ',' . $toLat;
  29. } else {
  30. $url = "http://restapi.amap.com/v5/direction/electrobike?key=" . self::$thirdMapKey . '&origin=' . $fromLnt . ',' . $fromLat . '&destination=' . $toLnt . ',' . $toLat;
  31. }
  32. $curl = new curl\Curl();
  33. $result = $curl->get($url);
  34. $result = Json::decode($result);
  35. $distance = 0;
  36. if (!empty($result['status']) && $result['status'] == 1) {
  37. $path = $result['route']['paths'] ?? [];
  38. $current = $path[0] ?? [];
  39. $distance = $current['distance'] ?? 0;
  40. } else {
  41. $infoCode = $result['infocode'] ?? '';
  42. $info = $result['info'] ?? '';
  43. noticeUtil::push("计算两地距离报错:{$infoCode} {$info}", '15280215347');
  44. util::fail('距离计算失败');
  45. }
  46. return $distance;
  47. }
  48. //计算客户到店距离,骑电动车 ssh 2026.7.30
  49. public static function calcShopDistanceByEleBike($beginPlace, $toPlace, $report = 1)
  50. {
  51. $beginLnt = $beginPlace->long ?? '';
  52. $beginLat = $beginPlace->lat ?? '';
  53. $toLnt = $toPlace->long ?? '';
  54. $toLat = $toPlace->lat ?? '';
  55. // 校验经纬度参数格式
  56. if (empty($beginLnt) || empty($beginLat)) {
  57. if ($report == 1) {
  58. util::fail('计算距离失败,请完善地址');
  59. }
  60. return ['distance' => 0, 'distanceKm' => 0];
  61. }
  62. if (!is_numeric($beginLnt) || !is_numeric($beginLat)) {
  63. if ($report == 1) {
  64. util::fail('计算距离失败,请完善地址');
  65. }
  66. return ['distance' => 0, 'distanceKm' => 0];
  67. }
  68. if (empty($toLnt) || empty($toLat)) {
  69. if ($report == 1) {
  70. util::fail('计算距离失败,商家地址没有完善');
  71. }
  72. return ['distance' => 0, 'distanceKm' => 0];
  73. }
  74. if (!is_numeric($toLnt) || !is_numeric($toLat)) {
  75. if ($report == 1) {
  76. util::fail('计算距离失败,商家地址没有完善');
  77. }
  78. return ['distance' => 0, 'distanceKm' => 0];
  79. }
  80. $distance = self::calculateDistance($beginLnt, $beginLat, $toLnt, $toLat);
  81. $distanceKm = bcdiv($distance, 1000, 2);
  82. return ['distance' => $distance, 'distanceKm' => $distanceKm];
  83. }
  84. /**
  85. * 批量计算多个起点到一个终点的距离 (高德 V3 距离测量接口)
  86. * @param array $origins 起点坐标数组,例如:[['lng' => '116.481028', 'lat' => '39.989643'], ...]
  87. * @param string $toLnt 终点经度
  88. * @param string $toLat 终点纬度
  89. * @param int $type 路径计算的方式和方法 (0:直线距离, 1:驾车, 3:步行)
  90. * @return array
  91. */
  92. public static function calculateBatchDistance($origins, $toLnt, $toLat, $type = 1)
  93. {
  94. if (empty($origins)) {
  95. return [];
  96. }
  97. // 将起点数组拼接成高德要求的格式: lng1,lat1|lng2,lat2
  98. $originStrs = [];
  99. foreach ($origins as $origin) {
  100. $originStrs[] = $origin['lng'] . ',' . $origin['lat'];
  101. }
  102. $originsParam = implode('|', $originStrs);
  103. $destinationParam = $toLnt . ',' . $toLat;
  104. $domain = getenv('YII_ENV') == 'production' ? 'https://restapi.amap.com' : 'http://restapi.amap.com';
  105. $url = $domain . "/v3/distance?key=" . self::$thirdMapKey . "&origins={$originsParam}&destination={$destinationParam}&type={$type}";
  106. $curl = new curl\Curl();
  107. $result = $curl->get($url);
  108. $result = \yii\helpers\Json::decode($result);
  109. $distances = [];
  110. if (!empty($result['status']) && $result['status'] == 1 && !empty($result['results'])) {
  111. foreach ($result['results'] as $index => $res) {
  112. // 返回的结果顺序与传入的 origins 顺序一致
  113. $distances[$index] = $res['distance'] ?? 0;
  114. }
  115. } else {
  116. noticeUtil::push("高德批量测距接口返回失败:" . json_encode($result) . " url:" . $url);
  117. }
  118. return $distances;
  119. }
  120. /**
  121. * 逆地址解析(高德),根据经纬度解析省市区与地址
  122. * @param string|float $lat 纬度
  123. * @param string|float $long 经度
  124. * @param string $locationType gcj02|wgs84,wgs84 时传 coordsys=gps 给高德
  125. * @return array
  126. */
  127. public static function resolveLocation($lat, $long, $locationType = 'gcj02')
  128. {
  129. $lat = (float)$lat;
  130. $long = (float)$long;
  131. if ($lat == 0 || $long == 0) {
  132. return [];
  133. }
  134. $domain = getenv('YII_ENV') == 'production' ? 'https://restapi.amap.com' : 'http://restapi.amap.com';
  135. // 高德 location 参数:经度,纬度
  136. $location = $long . ',' . $lat;
  137. $url = $domain . '/v3/geocode/regeo?location=' . urlencode($location)
  138. . '&key=' . self::$thirdMapKey
  139. . '&extensions=base';
  140. if ($locationType === 'wgs84' || $locationType === 'gps') {
  141. $url .= '&coordsys=gps';
  142. }
  143. $curl = new curl\Curl();
  144. $result = $curl->get($url);
  145. $result = Json::decode($result);
  146. return self::formatAmapRegeoResult($result);
  147. }
  148. /**
  149. * 格式化高德逆地理编码结果
  150. */
  151. private static function formatAmapRegeoResult($result)
  152. {
  153. if (empty($result['status']) || (string)$result['status'] !== '1' || empty($result['regeocode'])) {
  154. return [];
  155. }
  156. $regeo = $result['regeocode'];
  157. $component = $regeo['addressComponent'] ?? [];
  158. $province = self::normalizeAmapRegionValue($component['province'] ?? '');
  159. $city = self::normalizeAmapRegionValue($component['city'] ?? '');
  160. $district = self::normalizeAmapRegionValue($component['district'] ?? '');
  161. if (empty($city)) {
  162. $city = $province;
  163. }
  164. $showAddress = $regeo['formatted_address'] ?? '';
  165. $township = self::normalizeAmapRegionValue($component['township'] ?? '');
  166. $streetNumber = $component['streetNumber'] ?? [];
  167. $street = is_array($streetNumber) ? ($streetNumber['street'] ?? '') : '';
  168. $number = is_array($streetNumber) ? ($streetNumber['number'] ?? '') : '';
  169. $address = trim($township . $street . $number);
  170. if (empty($address)) {
  171. $address = $showAddress;
  172. if ($province && mb_strpos($address, $province) === 0) {
  173. $address = mb_substr($address, mb_strlen($province));
  174. }
  175. if ($city && $city !== $province && mb_strpos($address, $city) === 0) {
  176. $address = mb_substr($address, mb_strlen($city));
  177. }
  178. if ($district && mb_strpos($address, $district) === 0) {
  179. $address = mb_substr($address, mb_strlen($district));
  180. }
  181. $address = trim($address);
  182. }
  183. if (empty($address) || empty($province) || empty($city)) {
  184. return [];
  185. }
  186. return [
  187. 'province' => $province,
  188. 'city' => $city,
  189. 'district' => $district,
  190. 'address' => $address,
  191. 'showAddress' => $showAddress ?: ($province . $city . $district . $address),
  192. ];
  193. }
  194. /**
  195. * 根据经纬度获取当前位置及附近 POI 列表(高德逆地理 extensions=all)
  196. */
  197. public static function resolveNearby($lat, $long, $locationType = 'gcj02')
  198. {
  199. $lat = (float)$lat;
  200. $long = (float)$long;
  201. if ($lat == 0 || $long == 0) {
  202. return [];
  203. }
  204. $domain = getenv('YII_ENV') == 'production' ? 'https://restapi.amap.com' : 'http://restapi.amap.com';
  205. $location = $long . ',' . $lat;
  206. $url = $domain . '/v3/geocode/regeo?location=' . urlencode($location)
  207. . '&key=' . self::$thirdMapKey
  208. . '&extensions=all&radius=1000&roadlevel=0';
  209. if ($locationType === 'wgs84' || $locationType === 'gps') {
  210. $url .= '&coordsys=gps';
  211. }
  212. $curl = new curl\Curl();
  213. $result = Json::decode($curl->get($url));
  214. if (empty($result['status']) || (string)$result['status'] !== '1' || empty($result['regeocode'])) {
  215. return [];
  216. }
  217. $regeo = $result['regeocode'];
  218. $component = $regeo['addressComponent'] ?? [];
  219. $province = self::normalizeAmapRegionValue($component['province'] ?? '');
  220. $city = self::normalizeAmapRegionValue($component['city'] ?? '');
  221. $district = self::normalizeAmapRegionValue($component['district'] ?? '');
  222. if (empty($city)) {
  223. $city = $province;
  224. }
  225. $centerAddress = $regeo['formatted_address'] ?? '';
  226. $centerName = self::normalizeAmapRegionValue($component['township'] ?? '');
  227. if (empty($centerName)) {
  228. $centerName = '当前位置';
  229. }
  230. $list = [[
  231. 'name' => $centerName,
  232. 'address' => $centerAddress,
  233. 'province' => $province,
  234. 'city' => $city,
  235. 'district' => $district,
  236. 'location' => $long . ',' . $lat,
  237. 'showAddress' => $centerAddress,
  238. ]];
  239. $pois = $regeo['pois'] ?? [];
  240. $exists = [$centerName];
  241. foreach ($pois as $poi) {
  242. $poiName = $poi['name'] ?? '';
  243. if ($poiName === '' || in_array($poiName, $exists, true)) {
  244. continue;
  245. }
  246. $exists[] = $poiName;
  247. $poiAddress = $poi['address'] ?? '';
  248. if ($poiAddress === '') {
  249. $poiAddress = $centerAddress ? ($centerAddress . ' ' . $poiName) : $poiName;
  250. }
  251. $list[] = [
  252. 'name' => $poiName,
  253. 'address' => $poiAddress,
  254. 'province' => $province,
  255. 'city' => $city,
  256. 'district' => $district,
  257. 'location' => $poi['location'] ?? ($long . ',' . $lat),
  258. 'showAddress' => $poiAddress,
  259. ];
  260. if (count($list) >= 21) {
  261. break;
  262. }
  263. }
  264. return $list;
  265. }
  266. private static function normalizeAmapRegionValue($value)
  267. {
  268. if (is_array($value)) {
  269. return !empty($value) ? (string)$value[0] : '';
  270. }
  271. return (string)$value;
  272. }
  273. /**
  274. * 坐标系转换:从 WGS84 转换为 GCJ-02
  275. * @param $lng
  276. * @param $lat
  277. * @return array
  278. */
  279. public static function wgs84ToGcj02($lng, $lat)
  280. {
  281. $lng = (float)$lng;
  282. $lat = (float)$lat;
  283. if (self::outOfChina($lng, $lat)) {
  284. return ['lng' => $lng, 'lat' => $lat];
  285. }
  286. $a = 6378245.0;
  287. $ee = 0.00669342162296594323;
  288. $dLat = self::transformLat($lng - 105.0, $lat - 35.0);
  289. $dLng = self::transformLng($lng - 105.0, $lat - 35.0);
  290. $radLat = $lat / 180.0 * M_PI;
  291. $magic = sin($radLat);
  292. $magic = 1 - $ee * $magic * $magic;
  293. $sqrtMagic = sqrt($magic);
  294. $dLat = ($dLat * 180.0) / (($a * (1 - $ee)) / ($magic * $sqrtMagic) * M_PI);
  295. $dLng = ($dLng * 180.0) / ($a / $sqrtMagic * cos($radLat) * M_PI);
  296. return ['lng' => $lng + $dLng, 'lat' => $lat + $dLat];
  297. }
  298. private static function transformLat($lng, $lat)
  299. {
  300. $ret = -100.0 + 2.0 * $lng + 3.0 * $lat + 0.2 * $lat * $lat + 0.1 * $lng * $lat + 0.2 * sqrt(abs($lng));
  301. $ret += (20.0 * sin(6.0 * $lng * M_PI) + 20.0 * sin(2.0 * $lng * M_PI)) * 2.0 / 3.0;
  302. $ret += (20.0 * sin($lat * M_PI) + 40.0 * sin($lat / 3.0 * M_PI)) * 2.0 / 3.0;
  303. $ret += (160.0 * sin($lat / 12.0 * M_PI) + 320.0 * sin($lat * M_PI / 30.0)) * 2.0 / 3.0;
  304. return $ret;
  305. }
  306. private static function transformLng($lng, $lat)
  307. {
  308. $ret = 300.0 + $lng + 2.0 * $lat + 0.1 * $lng * $lng + 0.1 * $lng * $lat + 0.1 * sqrt(abs($lng));
  309. $ret += (20.0 * sin(6.0 * $lng * M_PI) + 20.0 * sin(2.0 * $lng * M_PI)) * 2.0 / 3.0;
  310. $ret += (20.0 * sin($lng * M_PI) + 40.0 * sin($lng / 3.0 * M_PI)) * 2.0 / 3.0;
  311. $ret += (150.0 * sin($lng / 12.0 * M_PI) + 300.0 * sin($lng / 30.0 * M_PI)) * 2.0 / 3.0;
  312. return $ret;
  313. }
  314. private static function outOfChina($lng, $lat)
  315. {
  316. if ($lng < 72.004 || $lng > 137.8347) {
  317. return true;
  318. }
  319. if ($lat < 0.8293 || $lat > 55.8271) {
  320. return true;
  321. }
  322. return false;
  323. }
  324. }