当存在types
设置为的结果时,您将在地理编码请求中找到此信息
[ "sublocality", "political" ]
示例:纽约市麦迪逊大街 317 号
修改上面的函数以便于访问响应组件:
/**
* @param $a mixed latitude or address
* @param $b mixed optional longitude when $a is latitude
* @return object geocoding-data
**/
function geocode($a, $b=null) {
$params=array('sensor'=>'false');
if(is_null($b))
{
$params['address']=$a;
}
else
{
$params['latlng']=implode(',',array($a,$b));
}
$url = 'http://maps.google.com/maps/api/geocode/json?'.http_build_query($params,'','&');
$result=@file_get_contents($url);
$response=new StdClass;
$response->street_address = null;
$response->route = null;
$response->country = null;
$response->administrative_area_level_1 = null;
$response->administrative_area_level_2 = null;
$response->administrative_area_level_3 = null;
$response->locality = null;
$response->sublocality = null;
$response->neighborhood = null;
$response->postal_code = null;
$response->formatted_address = null;
$response->latitude = null;
$response->longitude = null;
$response->status = 'ERROR';
if($result)
{
$json=json_decode($result);
$response->status=$json->status;
if($response->status=='OK')
{
$response->formatted_address=$json->results[0]->formatted_address;
$response->latitude=$json->results[0]->geometry->location->lat;
$response->longitude=$json->results[0]->geometry->location->lng;
foreach($json->results[0]->address_components as $value)
{
if(array_key_exists($value->types[0],$response))
{
$response->{$value->types[0]}=$value->long_name;
}
}
}
}
return $response;
}
//sample usage
echo '<hr/>'.geocode('317 Madison Ave,New York City')->sublocality;
//Manhattan
echo '<hr/>'.geocode('foobar')->status;
//ZERO_RESULTS
echo '<hr/>'.geocode('40.689758, -74.04513800000001')->formatted_address;
//1 Liberty Is, Brooklyn, NY 11231, USA