/
geonames.py
363 lines (302 loc) · 12.3 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
from functools import partial
from urllib.parse import urlencode
from geopy.exc import (
GeocoderAuthenticationFailure,
GeocoderInsufficientPrivileges,
GeocoderQueryError,
GeocoderQuotaExceeded,
GeocoderServiceError,
)
from geopy.geocoders.base import DEFAULT_SENTINEL, Geocoder
from geopy.location import Location
from geopy.timezone import (
ensure_pytz_is_installed,
from_fixed_gmt_offset,
from_timezone_name,
)
from geopy.util import logger
__all__ = ("GeoNames", )
class GeoNames(Geocoder):
"""GeoNames geocoder.
Documentation at:
http://www.geonames.org/export/geonames-search.html
Reverse geocoding documentation at:
http://www.geonames.org/export/web-services.html#findNearbyPlaceName
"""
geocode_path = '/searchJSON'
reverse_path = '/findNearbyPlaceNameJSON'
reverse_nearby_path = '/findNearbyJSON'
timezone_path = '/timezoneJSON'
def __init__(
self,
username,
*,
timeout=DEFAULT_SENTINEL,
proxies=DEFAULT_SENTINEL,
user_agent=None,
ssl_context=DEFAULT_SENTINEL,
adapter_factory=None,
scheme='http',
domain='api.geonames.org',
):
"""
:param str username: GeoNames username, required. Sign up here:
http://www.geonames.org/login
:param int timeout:
See :attr:`geopy.geocoders.options.default_timeout`.
:param dict proxies:
See :attr:`geopy.geocoders.options.default_proxies`.
:param str user_agent:
See :attr:`geopy.geocoders.options.default_user_agent`.
:type ssl_context: :class:`ssl.SSLContext`
:param ssl_context:
See :attr:`geopy.geocoders.options.default_ssl_context`.
:param callable adapter_factory:
See :attr:`geopy.geocoders.options.default_adapter_factory`.
.. versionadded:: 2.0
:param str scheme:
See :attr:`geopy.geocoders.options.default_scheme`. Note that
at the time of writing GeoNames doesn't support `https`, so
the default scheme is `http`. The value of
:attr:`geopy.geocoders.options.default_scheme` is not respected.
This parameter is present to make it possible to switch to
`https` once GeoNames adds support for it.
:param str domain: base api domain
.. versionadded:: 2.4
"""
super().__init__(
scheme=scheme,
timeout=timeout,
proxies=proxies,
user_agent=user_agent,
ssl_context=ssl_context,
adapter_factory=adapter_factory,
)
self.username = username
self.api = (
"%s://%s%s" % (self.scheme, domain, self.geocode_path)
)
self.api_reverse = (
"%s://%s%s" % (self.scheme, domain, self.reverse_path)
)
self.api_reverse_nearby = (
"%s://%s%s" % (self.scheme, domain, self.reverse_nearby_path)
)
self.api_timezone = (
"%s://%s%s" % (self.scheme, domain, self.timezone_path)
)
def geocode(
self,
query,
*,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
country=None,
country_bias=None
):
"""
Return a location point by address.
:param str query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
:param country: Limit records to the specified countries.
Two letter country code ISO-3166 (e.g. ``FR``). Might be
a single string or a list of strings.
:type country: str or list
:param str country_bias: Records from the country_bias are listed first.
Two letter country code ISO-3166.
:rtype: ``None``, :class:`geopy.location.Location` or a list of them, if
``exactly_one=False``.
"""
params = [
('q', query),
('username', self.username),
]
if country_bias:
params.append(('countryBias', country_bias))
if not country:
country = []
if isinstance(country, str):
country = [country]
for country_item in country:
params.append(('country', country_item))
if exactly_one:
params.append(('maxRows', 1))
url = "?".join((self.api, urlencode(params)))
logger.debug("%s.geocode: %s", self.__class__.__name__, url)
callback = partial(self._parse_json, exactly_one=exactly_one)
return self._call_geocoder(url, callback, timeout=timeout)
def reverse(
self,
query,
*,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
feature_code=None,
lang=None,
find_nearby_type='findNearbyPlaceName'
):
"""
Return an address by location point.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of ``(latitude,
longitude)``, or string as ``"%(latitude)s, %(longitude)s"``.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
:param str feature_code: A GeoNames feature code
:param str lang: language of the returned ``name`` element (the pseudo
language code 'local' will return it in local language)
Full list of supported languages can be found here:
https://www.geonames.org/countries/
:param str find_nearby_type: A flag to switch between different
GeoNames API endpoints. The default value is ``findNearbyPlaceName``
which returns the closest populated place. Another currently
implemented option is ``findNearby`` which returns
the closest toponym for the lat/lng query.
:rtype: ``None``, :class:`geopy.location.Location` or a list of them, if
``exactly_one=False``.
"""
try:
lat, lng = self._coerce_point_to_string(query).split(',')
except ValueError:
raise ValueError("Must be a coordinate pair or Point")
if find_nearby_type == 'findNearbyPlaceName': # default
if feature_code:
raise ValueError(
"find_nearby_type=findNearbyPlaceName doesn't support "
"the `feature_code` param"
)
params = self._reverse_find_nearby_place_name_params(
lat=lat,
lng=lng,
lang=lang,
)
url = "?".join((self.api_reverse, urlencode(params)))
elif find_nearby_type == 'findNearby':
if lang:
raise ValueError(
"find_nearby_type=findNearby doesn't support the `lang` param"
)
params = self._reverse_find_nearby_params(
lat=lat,
lng=lng,
feature_code=feature_code,
)
url = "?".join((self.api_reverse_nearby, urlencode(params)))
else:
raise GeocoderQueryError(
'`%s` find_nearby_type is not supported by geopy' % find_nearby_type
)
logger.debug("%s.reverse: %s", self.__class__.__name__, url)
callback = partial(self._parse_json, exactly_one=exactly_one)
return self._call_geocoder(url, callback, timeout=timeout)
def _reverse_find_nearby_params(self, lat, lng, feature_code):
params = {
'lat': lat,
'lng': lng,
'username': self.username,
}
if feature_code:
params['featureCode'] = feature_code
return params
def _reverse_find_nearby_place_name_params(self, lat, lng, lang):
params = {
'lat': lat,
'lng': lng,
'username': self.username,
}
if lang:
params['lang'] = lang
return params
def reverse_timezone(self, query, *, timeout=DEFAULT_SENTINEL):
"""
Find the timezone for a point in `query`.
GeoNames always returns a timezone: if the point being queried
doesn't have an assigned Olson timezone id, a ``pytz.FixedOffset``
timezone is used to produce the :class:`geopy.timezone.Timezone`.
:param query: The coordinates for which you want a timezone.
:type query: :class:`geopy.point.Point`, list or tuple of (latitude,
longitude), or string as "%(latitude)s, %(longitude)s"
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
:rtype: :class:`geopy.timezone.Timezone`.
"""
ensure_pytz_is_installed()
try:
lat, lng = self._coerce_point_to_string(query).split(',')
except ValueError:
raise ValueError("Must be a coordinate pair or Point")
params = {
"lat": lat,
"lng": lng,
"username": self.username,
}
url = "?".join((self.api_timezone, urlencode(params)))
logger.debug("%s.reverse_timezone: %s", self.__class__.__name__, url)
return self._call_geocoder(url, self._parse_json_timezone, timeout=timeout)
def _raise_for_error(self, body):
err = body.get('status')
if err:
code = err['value']
message = err['message']
# http://www.geonames.org/export/webservice-exception.html
if message.startswith("user account not enabled to use"):
raise GeocoderInsufficientPrivileges(message)
if code == 10:
raise GeocoderAuthenticationFailure(message)
if code in (18, 19, 20):
raise GeocoderQuotaExceeded(message)
raise GeocoderServiceError(message)
def _parse_json_timezone(self, response):
self._raise_for_error(response)
timezone_id = response.get("timezoneId")
if timezone_id is None:
# Sometimes (e.g. for Antarctica) GeoNames doesn't return
# a `timezoneId` value, but it returns GMT offsets.
# Apparently GeoNames always returns these offsets -- for
# every single point on the globe.
raw_offset = response["rawOffset"]
return from_fixed_gmt_offset(raw_offset, raw=response)
else:
return from_timezone_name(timezone_id, raw=response)
def _parse_json(self, doc, exactly_one):
"""
Parse JSON response body.
"""
places = doc.get('geonames', [])
self._raise_for_error(doc)
if not len(places):
return None
def parse_code(place):
"""
Parse each record.
"""
latitude = place.get('lat', None)
longitude = place.get('lng', None)
if latitude and longitude:
latitude = float(latitude)
longitude = float(longitude)
else:
return None
placename = place.get('name')
state = place.get('adminName1', None)
country = place.get('countryName', None)
location = ', '.join(
[x for x in [placename, state, country] if x]
)
return Location(location, (latitude, longitude), place)
if exactly_one:
return parse_code(places[0])
else:
return [parse_code(place) for place in places]