98 lines
2.8 KiB
PHP
98 lines
2.8 KiB
PHP
<?php
|
||
|
||
namespace Extend\Tencent\map;
|
||
|
||
use App\Constants\HttpEnumCode;
|
||
use App\Exception\BusinessException;
|
||
use GuzzleHttp\Client;
|
||
use GuzzleHttp\Exception\GuzzleException;
|
||
use Hyperf\Di\Annotation\Inject;
|
||
use Hyperf\Utils\ApplicationContext;
|
||
use Psr\Container\ContainerExceptionInterface;
|
||
use Psr\Container\ContainerInterface;
|
||
use Psr\Container\NotFoundExceptionInterface;
|
||
use function \Hyperf\Config\config;
|
||
/**
|
||
* 腾讯地图
|
||
*/
|
||
class Location
|
||
{
|
||
#[Inject]
|
||
protected ContainerInterface $container;
|
||
|
||
#[Inject]
|
||
protected Client $client;
|
||
|
||
/**
|
||
* @throws ContainerExceptionInterface
|
||
* @throws NotFoundExceptionInterface
|
||
*/
|
||
public function __construct()
|
||
{
|
||
$this->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" => $lat . "," . $lon,
|
||
];
|
||
|
||
$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());
|
||
}
|
||
}
|
||
} |