PHP 使用高德介面獲取地理編碼和逆地理編碼
- 2019 年 12 月 17 日
- 筆記
PHP 使用高德介面獲取地理編碼和逆地理編碼
產品介紹
地理編碼/逆地理編碼 API 是通過 HTTP/HTTPS 協議訪問遠程服務的介面,提供結構化地址與經緯度之間的相互轉化的能力。
適用場景
- 地理編碼:將詳細的結構化地址轉換為高德經緯度坐標。且支援對地標性名勝景區、建築物名稱解析為高德經緯度坐標。 結構化地址舉例:北京市朝陽區阜通東大街6號轉換後經緯度:116.480881,39.989410 地標性建築舉例:天安門轉換後經緯度:116.397499,39.908722
- 逆地理編碼:將經緯度轉換為詳細結構化的地址,且返回附近周邊的POI、AOI資訊。 例如:116.480881,39.989410 轉換地址描述後:北京市朝陽區阜通東大街6號
- 使用說明 第一步,申請Web服務API類型Key;
第二步,參考介面參數文檔發起HTTP/HTTPS請求,第一步申請的 Key 需作為必填參數一同發送;
第三步,接收請求返回的數據(JSON或XML格式),參考返回參數文檔解析數據。
如無特殊聲明,介面的輸入參數和輸出數據編碼全部統一為 UTF-8 編碼方式。
以上內容來自高德開放平台 地理逆地理編碼
基礎配置
項目需要使用請求高德介面,因此選擇來使用 guzzle/guzzle
來作為 http client
composer require guzzlehttp/guzzle
獲取地理編碼
use GuzzleHttpClient; 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 GuzzleHttpClient; 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(; } }