我有确切的地址(街道,无,城市,地区/区域,国家)的数据库。 不过,我想知道是否有使用谷歌API来获取一个城市(如“曼哈顿”)如果我们在纽约地区的一个方法是什么?
所有其他信息我已经在数据库中,所以我只需要该地区是否有一个(当然这将是只在较大的城市)...
更新:
我发现这个功能http://www.techques.com/question/1-3151450/Google-geolocation-API---Use-longitude-and-latitude-to-get-address并试图改变formatted_address
到sublocality(即使其他人一样SHORT_NAME等),但它不返回任何东西...任何帮助,将不胜感激! 谢谢!!
function reverse_geocode($lat, $lon) {
$url = "http://maps.google.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false";
$data = json_decode(file_get_contents($url));
if (!isset($data->results[0]->formatted_address)){
return "unknown Place";
}
return $data->results[0]->formatted_address;
}
您可以访问这样的sublocality:
function reverse_geocode($lat, $lon) {
$url = "http://maps.google.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false";
$data = json_decode(file_get_contents($url));
if (!isset($data->results[0]->address_components)){
return "unknown Place";
}
if ($data->results[0]->address_components[2]->types[0]=="sublocality") {
$return_array['type']="sublocality";
$return_array['sublocality_long_name']=$data->results[0]->address_components[2]->long_name;
$return_array['sublocality_short_name']=$data->results[0]->address_components[2]->short_name;
return $return_array;
}
}
你会发现一个地址解析请求这里面的信息,当存在与结果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