1. Skip to navigation
  2. Skip to content
  3. Skip to sidebar

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:

http://developer.yahoo.net/faq/index.html#appid

    Documentation for the Yahoo geocoding api can be found at:

http://developer.yahoo.net/maps/rest/V1/geocode.html

    """      
def init(self, appid, address_str):
    self.addressstr = addressstr
    self.addresses = []
    self.resultcount = 0
    parms = {’appid’: appid, ’location’: addressstr}

    try:
        url = ’http://api.local.yahoo.com/MapsService/V1/geocode?’+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
        else:
            d[itm.nodeName] = ’’
        self.addresses.append(d)
    except:
        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)
            %(Address)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.

Topics:
, ,
  • brian

    your code does not work.

  • Anonymous

    a bit outdated…
    you can use pygeocoder for lightweight geocoding and reverse geocoding

    it’s as simple as Geocoder.geocode(“Eiffel tower”)