使用带有完整地址的Google地理编码API从JSON返回多个值



我收到的输出

http://maps.google.com/maps/api/geocode/json?address={$address}

JSON格式。然后像这个一样拉经纬度

$lati = $resp['results'][0]['geometry']['location']['lat'];
$longi = $resp['results'][0]['geometry']['location']['lng'];

所有这些都非常有效。但我也需要这里包含的郡名

...
"results" : [
{
"address_components" : [
{
"long_name" : "Platte City",
"short_name" : "Platte City",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Carroll Township",
"short_name" : "Carroll Township",
"types" : [ "administrative_area_level_3", "political" ]
},
{
"long_name" : "Platte County",
"short_name" : "Platte County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Missouri",
"short_name" : "MO",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "64079",
"short_name" : "64079",
"types" : [ "postal_code" ]
}
],
...

我试过

for ($i = 0; $i < 10; $i++) {
$type2 = $resp['results'][0]['address_components'][$i]['types'];
if (stripos(strtolower($type2), 'administrative_area_level_2') !== false){
$county = $resp['results'][0]['address_components'][$i]['long_name'];
} else {$county = "$i Unknown County";}
}

正如你所看到的,县处于"administrative_area_level_2",但在尝试了几个小时后,我得到的只是"未知县"。Google API声明它不会总是在XML/JSON中的相同位置,这似乎是正确的。有时它在位置3,有时在位置5,有时在其他地方。有人能给我举个如何取县名的例子吗。

// Routine to find the County name
foreach ($resp['results'][0]['address_components'] as $comp) {
//loop through each component in ['address_components']     
foreach ($comp['types'] as $currType){          
//for every type in the current component, check if it = the check
if($currType == 'administrative_area_level_2'){
//echo $comp['long_name'];
$county = $comp['long_name'];
}           }
}

最新更新