我收到了
的输出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";}
}
正如你所看到的,县位于&#34; administrative_area_level_2&#34;但经过几个小时的努力,我得到的就是“未知县”#39; Google API声明它不会始终位于XML / JSON中的相同位置,而且似乎是正确的。有时它位于第3位,有时在5位有时在其他地方。 有人能给我一个如何获得县名的例子。
答案 0 :(得分:0)
// 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'];
} }
}