container = ApplicationContext::getContainer(); $this->client = $this->container->get(Client::class); } /** * 计算签名 * @param string $path * @param array $query * @return string */ private function getSign(string $path,array $query): string { ksort($query); // 拼接请求参数 $queryString = urldecode(http_build_query($query)); // 拼接签名字符串 $signatureStr = $path . '?' . $queryString . config("tencent_map.key"); // 计算签名,取MD5的小写形式 $sig = md5($signatureStr); // 将签名添加到参数中 $query['sig'] = $sig; return $path . '?' . http_build_query($query); } /** * 逆地址解析-根据经纬度获取地址 * @param string $lon 经度,范围为 -180~180,负数表示西经 * @param string $lat 纬度,范围为 -90~90,负数表示南纬 * @return array */ public function getLocation(string $lon,string $lat): array { $query = [ "key" => config("tencent_map.secret"), "location" => $lon . "," . $lat, ]; $path = "https://apis.map.qq.com" . $this->getSign("/ws/geocoder/v1",$query); try { $response = $this->client->get($path); if ($response->getStatusCode() != '200') { // 请求失败 throw new BusinessException($response->getBody()->getContents()); } $body = json_decode($response->getBody(), true); if (empty($body)) { // 返回值为空 throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR)); } if ($body['status'] != 0){ throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR)); } if (empty($body['result'])){ return []; } return $body['result']; } catch (GuzzleException $e) { throw new BusinessException($e->getMessage()); } } }