使用 Google 地理编码 API 和 return 来自 JSON 的几个值的完整地址

Using Google geocode API with full address to return several values from 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",但尝试了几个小时后,我得到的结果是 'Unknown County'。 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'];
                    }           }
            }