地理编码/逆地理编码 API 是通过 HTTP/HTTPS 协议访问远程服务的接口,提供结构化地址与经纬度之间的相互转化的能力。
第二步,参考接口参数文档发起HTTP/HTTPS请求,第一步申请的 Key 需作为必填参数一同发送;
第三步,接收请求返回的数据(JSON或XML格式),参考返回参数文档解析数据。
如无特殊声明,接口的输入参数和输出数据编码全部统一为 UTF-8 编码方式。
以上内容来自高德开放平台 地理逆地理编码
项目需要使用请求高德接口,因此选择来使用 guzzle/guzzle
来作为 http client
composer require guzzlehttp/guzzle
获取地理编码
use GuzzleHttp\Client;
public function getGeo($address, $city, $batch = false, $format = 'json')
{
$url = 'https://restapi.amap.com/v3/geocode/geo';
if (!\in_array(\strtolower($format), ['xml', 'json'])) {
return 'Invalid response format: '.$format;
}
$query = array_filter([
'key' => $this->key,
'address' => $address,
'city' => $city,
'batch' => $batch,
'output' => $format,
]);
try {
$client = new Client();
$response = $client->get($url, [
'query' => $query,
])->getBody()->getContents();
return 'json' === $format ? \json_decode($response, true) : $response;
} catch (\Exception $e) {
return $e->getCode();
}
}
具体参数请参考 地理/逆地理编码
获取逆地理编码
use GuzzleHttp\Client;
public function getRegeo($location, $poitype, $radius = 1000, $type = 'all', $batch = false, $roadlevel = 0, $format = 'json')
{
$url = 'https://restapi.amap.com/v3/geocode/regeo';
if (!\in_array(\strtolower($format), ['xml', 'json'])) {
return 'Invalid response format: '.$format;
}
$radius = intval($radius);
if ($radius < 0 || $radius > 3000) {
return 'Invalid radius value(0~3000): '.$radius;
}
$query = array_filter([
'key' => $this->key,
'location' => $location,
'poitype' => $poitype,
'radius' => $radius,
'extensions' => $type,
'batch' => $batch,
'roadlevel' => $roadlevel,
'output' => $format,
]);
try {
$client = new Client();
$response = $client->get($url, [
'query' => $query,
])->getBody()->getContents();
return 'json' === $format ? \json_decode($response, true) : $response;
} catch (\Exception $e) {
return $e->getCode(;
}
}