-
Notifications
You must be signed in to change notification settings - Fork 11
/
geonames.py
executable file
·90 lines (65 loc) · 2.08 KB
/
geonames.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import json
import urllib
import urllib2
#Csaba's code
class Geonames:
NAME, LON, LAT, COUNTRYCODE, COUNTRYNAME, ALTITUDE, GMTOFFS = range(0, 7)
username='morinus'
langs = ("en", "hu", "it", "fr", "ru", "es")
def __init__(self, city, maxnum, langid):
self.city = city
self.maxnum = maxnum
self.langid = langid
self.li = None
def fetch_values_from_page(self, url, params, key):
url = url % urllib.urlencode(params)
try:
page = urllib2.urlopen(url)
doc = json.loads(page.read())
values = doc.get(key, None)
except Exception, e:
values = None
# print(e)
return values
def get_basic_info(self, city):
url = "http://api.geonames.org/searchJSON?%s"
params = {
"username" : self.username,
"lang" : Geonames.langs[self.langid],
"q" : city,
"featureClass" : "P",
"maxRows" : self.maxnum
}
return self.fetch_values_from_page(url, params, "geonames")
def get_gmt_offset(self, longitude, latitude):
url = "http://api.geonames.org/timezoneJSON?%s"
params = {
"username" : self.username,
"lng" : longitude,
"lat" : latitude
}
return self.fetch_values_from_page(url, params, "rawOffset")
def get_elevation(self, longitude, latitude):
url = "http://api.geonames.org/astergdemJSON?%s"
params = {
"username" : self.username,
"lng" : longitude,
"lat" : latitude
}
return self.fetch_values_from_page(url, params, "astergdem")
def get_location_info(self):
info = self.get_basic_info(self.city)
if not info:
return False
self.li = []
for it in info:
longitude = it.get("lng", 0)
latitude = it.get("lat", 0)
placename = it.get("name", "")
country_code = it.get("countryCode", "")
country_name = it.get("countryName", "")
gmt_offset = self.get_gmt_offset(longitude, latitude)
elevation = self.get_elevation(longitude, latitude)
self.li.append((placename.encode("utf-8"), float(longitude), float(latitude),
country_code.encode("utf-8"), country_name.encode("utf-8"), elevation, gmt_offset))
return True