当前位置: 首页 > 后端技术 > PHP

从地址字符串获取省市信息

时间:2023-03-30 01:44:04 PHP

要求:从手填的地址,分析省市信息。使用百度地图api正向/反向地理编码PS:虽然百度地图提供了位置检索,但是需要传入行政区域信息。根据正向地理编码服务接口,将地址转换为经纬度,再根据经纬度调用反向地理编码服务接口,得到结构化行政区域信息codedefine("BAIDU_MAP_AK","YourBaiduMapAK");functionparse_address($string){try{$url="http://api.map.baidu.com/geocoder/v2/";$params=['address'=>$string,'output'=>"json",'ak'=>BAIDU_MAP_AK,];$网址。=“?”.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);返回@$json['result']['addressComponent'];}}返回空值;}catch(\Exception$e){返回空;}}//返回结果数组('country'=>'China','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','方向'=>'附近','距离'=>'33',);