mapUtil.php 13 KB

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