Reputation: 2915
I am using the following to get a the lat-lng from a geocode..
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
How do I extract the Postal code from ...
{
"status": "OK",
"results": [ {
"types": [ "street_address" ],
"formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"address_components": [ {
"long_name": "1600",
"short_name": "1600",
"types": [ "street_number" ]
}, {
"long_name": "Amphitheatre Pkwy",
"short_name": "Amphitheatre Pkwy",
"types": [ "route" ]
}, {
"long_name": "Mountain View",
"short_name": "Mountain View",
"types": [ "locality", "political" ]
}, {
"long_name": "California",
"short_name": "CA",
"types": [ "administrative_area_level_1", "political" ]
}, {
"long_name": "United States",
"short_name": "US",
"types": [ "country", "political" ]
}, {
"long_name": "94043",
"short_name": "94043",
"types": [ "postal_code" ]
} ],
"geometry": {
"location": {
"lat": 37.4219720,
"lng": -122.0841430
},
"location_type": "ROOFTOP",
"viewport": {
"southwest": {
"lat": 37.4188244,
"lng": -122.0872906
},
"northeast": {
"lat": 37.4251196,
"lng": -122.0809954
}
}
}
} ]
}
Upvotes: 9
Views: 6197
Reputation: 12408
You could use the following function to extract any address component:
function extractFromAdress(components, type){
for (var i=0; i<components.length; i++)
for (var j=0; j<components[i].types.length; j++)
if (components[i].types[j]==type) return components[i].long_name;
return "";
}
To extract the postal code you call:
extractFromAdress(results[0].address_components, "postal_code");
But you could also get other interesting info like:
extractFromAdress(results[0].address_components, "route");
extractFromAdress(results[0].address_components, "locality");
extractFromAdress(results[0].address_components, "country");
etc...
Upvotes: 13
Reputation: 31930
I'd say you'd need to loop through results.address_components
. On each iteration check if the types array contains "postal_code". If it does, save that to a variable, and probably break out of the loop as well. Although it might be worth investigating to see if the postal_code is always in address_component[5], which would save you having to loop.
Upvotes: 0