2
from urllib import urlencode
3
from urllib2 import urlopen, HTTPError
5
from geopy import Point, Location
6
from geopy.geocoders.base import Geocoder
9
class OSMGazetteer(Geocoder):
11
BASE_URL = "http://nominatim.openstreetmap.org/?%s"
13
def __init__(self, format_string='%s', viewbox=(-180,-90,180,90)):
14
self.format_string = format_string
15
self.viewbox = ','.join(map(str, viewbox))
16
self.output_format = 'json'
18
def geocode(self, string):
19
params = {'q': self.format_string % string,
20
'format': self.output_format,
21
'viewbox': self.viewbox
23
url = self.BASE_URL % urlencode(params)
24
return self.geocode_url(url)
26
def geocode_url(self, url):
27
print "Fetching %s..." % url
28
page = urlopen(url).read()
30
parse = getattr(self, 'parse_' + self.output_format)
33
def parse_json(self, page):
34
attribution, sep, page = page.partition("\n")
35
results = simplejson.loads(page)
37
def parse_result(result):
38
location = result.get('display_name')
39
latitude = result.get('lat')
40
longitude = result.get('lon')
41
if latitude and longitude:
42
point = Point(latitude, longitude)
45
return Location(location, point, result)
47
return [parse_result(result) for result in results]