I receive the output of
http://maps.google.com/maps/api/geocode/json?address={$address}
in JSON format. Then pull the latitude and longitude like this
$lati = $resp['results'][0]['geometry']['location']['lat'];
$longi = $resp['results'][0]['geometry']['location']['lng'];
All of which works great. But I also need the County name which is contained here
...
"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" ]
}
],
...
I tried
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";}
}
As you can see County is in "administrative_area_level_2" but after trying for several hours all I get is 'Unknown County'. The Google API states that it will not always be in the same location in the XML/JSON and that seems to be correct. Sometimes its at position 3 sometimes at 5 sometimes other places. Can someone give me an example of how to get the County name.
// 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'];
} }
}