Python Geocoding Help

Yahoo recently released a nifty geocoder API that’s free for small (<50,000 lookups per day), non-commercial applications. Rasmus Lerdorf (Yahoo’s PHP king) has written a nice introduction to using this geocoder in your PHP apps. In that spirit, here’s a cheap and cheerful Python class that we use to geocode addresses.

from xml.dom.minidom import parse 
import urllib  

class Geocoder:
    look up an location using the Yahoo geocoding api
    Requires a Yahoo appid which can be obtained at:
    Documentation for the Yahoo geocoding api can be found at:
def init(self, appid, address_str):
    self.addressstr = addressstr         
    self.addresses = []
    self.resultcount = 0         
    parms = {’appid’: appid, ’location’: addressstr}

        url = ’’+urllib.urlencode(parms)
        # parse the xml contents of the url into a dom
        dom = parse(urllib.urlopen(url))
        results = dom.getElementsByTagName(’Result’)
        self.result_count = len(results)
        for result in results:
            d = {’precision’: result.getAttribute(’precision’),
                ’warning’: result.getAttribute(’warning’)}

        for itm in result.childNodes:
            # if precision is zip, Address childNode will not exist

        if itm.childNodes:
            d[itm.nodeName] = itm.childNodes[0].data                     
            d[itm.nodeName] = ’’                
        raise "GeocoderError"      

def repr(self):
    s = "Original address:n%snn"%self.addressstr         
    s += "%d match(s) found:nn"%self.resultcount         
    for addr in self.addresses:
        s += """Match precision: %(precision)s
            Location: (%(Latitude)s,%(Longitude)s)
            %(City)s, %(State)s %(Zip)s
        """ % addr         
    return s

if name == "__main__": sample_addresses = [’555 Grove St. Herndon,VA 20170’, ’1234 Greeley blvd, springfeld, va, 22152’, ’50009’] for addr in sample_addresses: g = Geocoder(’YahooDemo’, addr) print ’-’*80
print g

All you need to use this is a Yahoo application id.

You now have four different ways to geocode your company’s vital address. If you have suggestions or improvements, let us know. This code is public domain.