php
Parse Addresses in
PHP using Google
Geocoding

What we want to do is send in an address that is all on one line and get back an array that has four elements, one for address, city, state, and one for postal code/zip.
So, here's how to do it (less than 2,500 times per day at time of writing):
function parse_address_google($address) {
$url = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address='.urlencode($address);
$results = json_decode(file_get_contents($url),1);
//die('<pre>'.print_r($results,true));
$parts = array(
'address'=>array('street_number','route'),
'city'=>array('locality'),
'state'=>array('administrative_area_level_1'),
'zip'=>array('postal_code'),
);
if (!empty($results['results'][0]['address_components'])) {
$ac = $results['results'][0]['address_components'];
foreach($parts as $need=>&$types) {
foreach($ac as &$a) {
if (in_array($a['types'][0],$types)) $address_out[$need] = $a['short_name'];
elseif (empty($address_out[$need])) $address_out[$need] = '';
}
}
} else echo 'empty results';
return $address_out;
}
Hopefully I'll have time to come back and write about how the internals of this work, but pretty much, you were looking for a small snippet that you could run with, so, there you have it, my friend. Go get your Geocode on and parse addresses in PHP!
Last Updated: 2011-12-20 22:45:19
