從地址字符串獲取省市區信息

需求:

從手工填寫的地址中,解析出省市區信息

方法

使用百度地圖api
/ 地理編碼
PS: 雖然百度地圖提供 地點檢索,可是是須要傳入行政區信息的

根據 正地理編碼服務 接口 將地址轉換爲經緯度,而後根據經緯度調用 逆地理編碼服務 接口,獲得結構化的行政區信息php

代碼

define("BAIDU_MAP_AK", "你的百度地圖AK");
function parse_address($string){
    try{
        $url = "http://api.map.baidu.com/geocoder/v2/";
        $params = [
            'address' => $string,
            'output' => "json",
            'ak' => BAIDU_MAP_AK,
        ];
        $url .= "?" . http_build_query($params);
        $json = json_decode(file_get_contents($url), true);
        if($loc = @$json['result']['location']){
            if(!is_null($loc)){
                $url = "http://api.map.baidu.com/geocoder/v2/";
                $params = [
                    'location' => "{$loc['lat']},{$loc['lng']}",
                    'output' => "json",
                    'ak' => BAIDU_MAP_AK,
                ];
                $url .= "?" . http_build_query($params);
                $json = json_decode(file_get_contents($url), true);
                return @$json['result']['addressComponent'];
            }
        }
        return null;
    }catch(\Exception $e){
        return null;
    }
}

//返回結果
array (
  'country' => '中國',
  'country_code' => 0,
  'country_code_iso' => 'CHN',
  'country_code_iso2' => 'CN',
  'province' => '福建省',
  'city' => '廈門市',
  'city_level' => 2,
  'district' => 'XX區',
  'town' => '',
  'adcode' => '350206',
  'street' => 'XX路',
  'street_number' => '26',
  'direction' => '附近',
  'distance' => '33',
);
相關文章
相關標籤/搜索