mootools php faith camera linux

php

Parse Addresses in
PHP using Google
Geocoding



Google's Geocoding API is awesome and easy to useNeed to parse the city, state, zip and address out of a one-liner? Use this Google GeoCoding API. GeoCoding means turning an address into some other format, most specifically latitude and longitude, and the API does much more than is demonstrated here.

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
Creative Commons License Jay Johnston is a Zend Certified Engineer in PHP 5 LPI-ID: LPI000102450, Verfication Code: wmnnt56y2k  ... Jay Johnston is certified as LPIC-1 by the Linux Professional Institute