Yahoo PlaceFinder Code

71 views
Skip to first unread message

Brandon Diamond

unread,
Jun 27, 2010, 12:58:46 AM6/27/10
to geopy
Hi all,

Absolutely love geopy -- but not the licensing/performance offered by
some of the geocoding services. Recently learned of Yahoo's new
geocoding web service, PlaceFinder, and quickly whipped up a very
simple geocoder module in python. PlaceFinder appears to have some
very favorable licencing terms and excellent response times so there
ya go.

I'm not really deep enough into geopy to implement this directly but
thought some of you might appreciate the code, which is as follows:

===== 8< =====

# Written by Brandon Diamond
# Released into the public domain

import urllib

from django.conf import settings
from django.utils import simplejson as json

class YahooException(Exception):
pass

# interface that behaves similarly to geopy's geocoders
class YahooGeocode(object):
@classmethod
def strip_result(cls, result):
if not result['postal']:
result['postal'] = result.get('uzip', '')

place = '%(city)s, %(statecode)s %(postal)s' % result

# return things in a geopy compatible format
return place, (float(result['latitude']),
float(result['longitude']))

def geocode(self, query, exactly_one=False):
try:
results = [YahooGeocode.strip_result(r) for r in
placefind(query)]
return results[0] if exactly_one else results

except YahooException:
return None


def placefind(query):
file = urllib.urlopen("http://where.yahooapis.com/geocode?%s" %
urllib.urlencode({
'appid': settings.YAHOO_APP_ID,
'flags': 'j',
'q': query
}))

try:
result = json.loads(file.read())
return result['ResultSet']['Results']
except:
raise YahooException()
finally:
file.close()
Reply all
Reply to author
Forward
0 new messages