-
Notifications
You must be signed in to change notification settings - Fork 62
/
geocoder.py
executable file
·52 lines (42 loc) · 1.3 KB
/
geocoder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/python
#
# Copyright 2012 Foursquare Labs Inc.
#
# Wrapper for the geocoder for use from python.
import re, json, sys, urllib, urllib2
class Geocode:
# Initialize from a raw interpretation from the geocoder service.
def __init__(self, interpretation):
self.interp = interpretation
def bounds(self):
try:
return self.interp['feature']['geometry']['bounds']
except:
return None
def what(self):
return self.interp['what']
def lat(self):
return self.interp['feature']['geometry']['center']['lat']
def lng(self):
return self.interp['feature']['geometry']['center']['lng']
def displayName(self):
return self.interp['feature']['displayName']
def ids(self):
return self.interp['feature']['ids']
def geonameid(self):
for i in self.ids():
if i['source'] == 'geonameid':
return i['id']
return None
class Geocoder:
def __init__(self, host):
self.host = host
def geocode(self, query, otherParams = {}):
otherParams['query'] = query
url = 'http://%s/?%s' % (self.host, urllib.urlencode(otherParams))
request = urllib2.Request(url)
response = json.loads(urllib2.urlopen(request).read())
if len(response['interpretations']) > 0:
return Geocode(response['interpretations'][0])
else:
return None