2017-08-30 127 views
0

返回幾個值,我收到的全地址使用谷歌的地理編碼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,有時候是其他地方。 有人可以給我一個如何獲得縣名的例子。

回答

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']; 
        }   } 
      }