Wednesday, June 10, 2009

From Address to Picture, in DC.

For anyone playing with the DC 311 API, I threw the following classes together in a furious bout of coding over the past half an hour while rocking a baby to sleep. I'm using it in a little throwaway app to show how you can pass an address into the DC 311 API and get an image of the building at that address. Their geocoding is not perfect (after all, this is a beta) but it does work for many DC addresses. And yes, the API currently uses "inage_url" (sic) but I expect Dmitry will fix that when he gets around to it.

class GeocodedAddress(object):
def __init__(self, address, image_url, confidence, latitude, longitude):
self.address = address
self.image_url = image_url
self.confidence = confidence
self.latitude = latitude
self.longitude = longitude

class DCGeocoder(object):
api_url = 'http://api.dc.gov/geocoding/v1/search.json'
def geocode(address):
url = '%s?%s' % (DCGeocoder.api_url,
urllib.urlencode({'address':address}))
response = urllib2.urlopen(url)
response = json.loads(response.read())

addresses = []
for addy in response['addresses']:
address = {}
for attribute in addy['address']:
address.update(attribute)

addresses.append(
GeocodedAddress(address['fulladdress'],
'%s/%s/%s' % (address['inageurl'], address['imagedir'],
address['imagename']), address['confidencelevel'],
address['latitude'], address['longitude']))
return addresses
geocode = staticmethod(geocode)

To use this, I'd do something like:
>>> print DCGeocoder.geocode('1 dupont circle, nw')[0].image_url