desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'YahooPlaceFinder.geocode unicode'
def test_unicode_name(self):
self.geocode_run({'query': u('\\u6545\\u5bab')}, {'latitude': 39.916, 'longitude': 116.39})
'YahooPlaceFinder.reverse string'
def test_reverse_string(self):
self.reverse_run({'query': '40.75376406311989, -73.98489005863667'}, {'latitude': 40.75376406311989, 'longitude': (-73.98489005863667)})
'YahooPlaceFinder.reverse Point'
def test_reverse_point(self):
self.reverse_run({'query': Point(40.75376406311989, (-73.98489005863667))}, {'latitude': 40.75376406311989, 'longitude': (-73.98489005863667)})
'YahooPlacefinder.with_timezone'
def test_timezone(self):
self.geocode_run({'query': 'nyc', 'with_timezone': True}, {'latitude': 40.71455, 'longitude': (-74.00712)})
'Baidu.geocode'
def test_basic_address(self):
self.geocode_run({'query': u('\\u5317\\u4eac\\u5e02\\u6d77\\u6dc0\\u533a\\u4e2d\\u5173\\u6751\\u5927\\u885727\\u53f7')}, {'latitude': 39.983615544507, 'longitude': 116.32295155093})
'Baidu.reverse address'
def test_reverse_address(self):
self.reverse_run({'query': u('\\u5317\\u4eac\\u5e02\\u6d77\\u6dc0\\u533a\\u4e2d\\u5173\\u6751\\u5927\\u885727\\u53f7')}, {'latitude': 39.983615544507, 'longitude': 116.32295155093})
'Baidu.reverse Point'
def test_reverse_point(self):
self.reverse_run({'query': Point(39.983615544507, 116.32295155093)}, {'latitude': 39.983615544507, 'longitude': 116.32295155093})
'OpenCage.geocode'
def test_geocode(self):
self.geocode_run({'query': '435 north michigan ave, chicago il 60611 usa'}, {'latitude': 41.89, 'longitude': (-87.624)})
'OpenCage.geocode unicode'
def test_unicode_name(self):
self.geocode_run({'query': u('\\u6545\\u5bab')}, {'latitude': 39.916, 'longitude': 116.39})
'Empty OpenCage.geocode results should be graciously handled.'
def test_geocode_empty_result(self):
self.geocode_run({'query': 'xqj37'}, {}, expect_failure=True)
'Test of OTB Geocoder Proxy functionality works'
def test_proxy(self):
class DummyGeocoder(Geocoder, ): def geocode(self, location): geo_request = urlopen(location) geo_html = geo_request.read() return (geo_html if geo_html else None) geocoder_dummy = DummyGeocoder(proxies={'http': 'http://localhost:1337'}) try: self.assertTrue(self.noproxy_data, geocoder_dummy.geocode('http://www.blankwebsite.com/')) except URLError as err: if ('connection refused' in str(err).lower()): raise unittest.SkipTest('Proxy not running') raise err
'Point() floats'
def test_point_float(self):
point = Point(self.lat, self.lon, self.alt) self.assertEqual(point.longitude, self.lon) self.assertEqual(point.latitude, self.lat) self.assertEqual(point.altitude, self.alt)
'Point() str'
def test_point_str_simple(self):
for each in ('%s,%s', '%s %s', '%s;%s'): point = Point((each % (self.lat, self.lon))) self.assertEqual(point.longitude, self.lon) self.assertEqual(point.latitude, self.lat)
'Point() str degrees, minutes &c'
def test_point_str_deg(self):
point = Point(u("UT: N 39\xb020' 0'' / W 74\xb035' 0''")) self.assertEqual(point.latitude, 39.333333333333336) self.assertEqual(point.longitude, (-74.58333333333333)) self.assertEqual(point.altitude, 0)
'Point.format()'
def test_point_format(self):
point = Point('51 19m 12.9s N, 0 1m 24.95s E') self.assertEqual(point.format(), '51 19m 12.9s N, 0 1m 24.95s E')
'Point.format() includes altitude'
def test_point_format_altitude(self):
point = Point(latitude=41.5, longitude=81.0, altitude=2.5) self.assertEqual(point.format(), '41 30m 0s N, 81 0m 0s E, 2.5km')
'Point.__getitem__'
def test_point_getitem(self):
point = Point(self.lat, self.lon, self.alt) self.assertEqual(point[0], self.lat) self.assertEqual(point[1], self.lon) self.assertEqual(point[2], self.alt)
'Point.__setitem__'
def test_point_setitem(self):
point = Point((self.lat + 10), (self.lon + 10), (self.alt + 10)) for each in (0, 1, 2): point[each] = (point[each] - 10) self.assertEqual(point[0], self.lat) self.assertEqual(point[1], self.lon) self.assertEqual(point[2], self.alt)
'Point.__eq__'
def test_point_eq(self):
self.assertEqual(Point(self.lat, self.lon), Point(('%s %s' % (self.lat, self.lon))))
'Point.__ne__'
def test_point_ne(self):
self.assertTrue((Point(self.lat, self.lon, self.alt) != Point((self.lat + 10), (self.lon - 10), self.alt)))
'format_degrees'
@unittest.skip('') def test_format(self):
self.assertEqual(format_degrees(Point.parse_degrees('-13', '19', 0)), '-13 19\' 0.0"')
'Initialize a customized SmartyStreets LiveAddress geocoder. :param string auth_id: Valid `Auth ID` from SmartyStreets. .. versionadded:: 1.5.0 :param string auth_token: Valid `Auth Token` from SmartyStreets. :param int candidates: An integer between 1 and 10 indicating the max number of candidate addresses to return if a valid address could be found. :param string scheme: Use \'https\' or \'http\' as the API URL\'s scheme. Default is https. Note that SSL connections\' certificates are not verified. .. versionadded:: 0.97 .. versionchanged:: 1.8.0 LiveAddress now requires `https`. Specifying `scheme=http` will result in a :class:`geopy.exc.ConfigurationError`. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising an :class:`geopy.exc.GeocoderTimedOut` exception. .. versionadded:: 0.97 :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`. .. versionadded:: 0.96'
def __init__(self, auth_id, auth_token, candidates=1, scheme=DEFAULT_SCHEME, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
super(LiveAddress, self).__init__(timeout=timeout, proxies=proxies, user_agent=user_agent) if (scheme == 'http'): raise ConfigurationError('LiveAddress now requires `https`.') self.scheme = scheme self.auth_id = auth_id self.auth_token = auth_token if candidates: if (not (1 <= candidates <= 10)): raise ValueError('candidates must be between 1 and 10') self.candidates = candidates self.api = ('%s://api.smartystreets.com/street-address' % self.scheme)
'Geocode a location query. :param string query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available.'
def geocode(self, query, exactly_one=True, timeout=None):
url = self._compose_url(query) logger.debug('%s.geocode: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'LiveStreets-specific exceptions.'
def _geocoder_exception_handler(self, error, message):
if ('no active subscriptions found' in message.lower()): raise GeocoderQuotaExceeded(message)
'Generate API URL.'
def _compose_url(self, location):
query = {'auth-id': self.auth_id, 'auth-token': self.auth_token, 'street': location, 'candidates': self.candidates} return '{url}?{query}'.format(url=self.api, query=urlencode(query))
'Parse responses as JSON objects.'
def _parse_json(self, response, exactly_one=True):
if (not len(response)): return None if (exactly_one is True): return self._format_structured_address(response[0]) else: return [self._format_structured_address(c) for c in response]
'Pretty-print address and return lat, lon tuple.'
@staticmethod def _format_structured_address(address):
latitude = address['metadata'].get('latitude') longitude = address['metadata'].get('longitude') return Location(', '.join((address['delivery_line_1'], address['last_line'])), ((latitude, longitude) if (latitude and longitude) else None), address)
':param string username: :param string password: :param string format_string: String containing \'%s\' where the string to geocode should be interpolated before querying the geocoder. For example: \'%s, Mountain View, CA\'. The default is just \'%s\'. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising an :class:`geopy.exc.GeocoderTimedOut` exception. .. versionadded:: 0.97 :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`. .. versionadded:: 0.96'
def __init__(self, username=None, password=None, format_string=DEFAULT_FORMAT_STRING, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
super(GeocoderDotUS, self).__init__(format_string=format_string, timeout=timeout, proxies=proxies, user_agent=user_agent) if (username or password): if (not (username and password)): raise ConfigurationError('Username and password must both specified') self.authenticated = True self.api = 'http://geocoder.us/member/service/namedcsv' else: self.authenticated = False self.api = 'http://geocoder.us/service/namedcsv' self.username = username self.password = password
'Geocode a location query. :param string 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. .. versionadded:: 0.97'
def geocode(self, query, exactly_one=True, timeout=None):
query_str = (self.format_string % query) url = '?'.join((self.api, urlencode({'address': query_str}))) logger.debug('%s.geocode: %s', self.__class__.__name__, url) if (self.authenticated is True): auth = ' '.join(('Basic', encodestring(':'.join((self.username, self.password)).encode('utf-8')).strip().decode('utf-8'))) url = Request(url, headers={'Authorization': auth}) page = self._call_geocoder(url, timeout=timeout, raw=True) content = (page.read().decode('utf-8') if py3k else page.read()) places = [r for r in csv.reader(([content] if (not isinstance(content, list)) else content))] if (not len(places)): return None if (exactly_one is True): return self._parse_result(places[0]) else: result = [self._parse_result(res) for res in places] if (None in result): return None return result
'Parse individual results. Different, but lazy actually, so... ok.'
@staticmethod def _parse_result(result):
place = dict([x.split('=') for x in result if (len(x.split('=')) > 1)]) if ('error' in place): if ("couldn't find" in place['error']): return None address = [place.get('number', None), place.get('prefix', None), place.get('street', None), place.get('type', None), place.get('suffix', None)] city = place.get('city', None) state = place.get('state', None) zip_code = place.get('zip', None) name = join_filter(', ', [join_filter(' ', address), city, join_filter(' ', [state, zip_code])]) latitude = place.get('lat', None) longitude = place.get('long', None) if (latitude and longitude): latlon = (float(latitude), float(longitude)) else: return None return Location(name, latlon, place)
':param string format_string: String containing \'%s\' where the string to geocode should be interpolated before querying the geocoder. For example: \'%s, Mountain View, CA\'. The default is just \'%s\'. :param tuple boundary_rect: Coordinates to restrict search within, given as (west, south, east, north) coordinate tuple. :param string country_bias: Bias results to this country (ISO alpha-3). :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`. .. versionadded:: 0.96'
def __init__(self, api_key, format_string=DEFAULT_FORMAT_STRING, boundary_rect=None, country_bias=None, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
super(Mapzen, self).__init__(format_string, 'https', timeout, proxies, user_agent=user_agent) self.country_bias = country_bias self.format_string = format_string self.boundary_rect = boundary_rect self.api_key = api_key self.geocode_api = 'https://search.mapzen.com/v1/search' self.reverse_api = 'https://search.mapzen.com/v1/reverse'
'Geocode a location query. :param query: The address, query or structured query to geocode you wish to geocode. :type query: string :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. .. versionadded:: 0.97'
def geocode(self, query, exactly_one=True, timeout=None):
params = {'text': (self.format_string % query)} params.update({'api_key': self.api_key}) if self.boundary_rect: params['boundary.rect.min_lon'] = self.boundary_rect[0] params['boundary.rect.min_lat'] = self.boundary_rect[1] params['boundary.rect.max_lon'] = self.boundary_rect[2] params['boundary.rect.max_lat'] = self.boundary_rect[3] if self.country_bias: params['boundary.country'] = self.country_bias url = '?'.join((self.geocode_api, urlencode(params))) logger.debug('%s.geocode_api: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Returns a reverse geocoded location. :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. .. versionadded:: 0.97'
def reverse(self, query, exactly_one=True, timeout=None):
try: (lat, lon) = [x.strip() for x in self._coerce_point_to_string(query).split(',')] except ValueError: raise ValueError('Must be a coordinate pair or Point') params = {'point.lat': lat, 'point.lon': lon, 'api_key': self.api_key} url = '?'.join((self.reverse_api, urlencode(params))) logger.debug('%s.reverse: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Parse each resource.'
@staticmethod def parse_code(feature):
latitude = feature.get('geometry', {}).get('coordinates', [])[1] longitude = feature.get('geometry', {}).get('coordinates', [])[0] placename = feature.get('properties', {}).get('name') return Location(placename, (latitude, longitude), feature)
'Initialize an Open MapQuest geocoder with location-specific address information. No API Key is needed by the Nominatim based platform. :param string format_string: String containing \'%s\' where the string to geocode should be interpolated before querying the geocoder. For example: \'%s, Mountain View, CA\'. The default is just \'%s\'. :param string scheme: Use \'https\' or \'http\' as the API URL\'s scheme. Default is https. Note that SSL connections\' certificates are not verified. .. versionadded:: 0.97 :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. .. versionadded:: 0.97 :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`. .. versionadded:: 0.96'
def __init__(self, api_key=None, format_string=DEFAULT_FORMAT_STRING, scheme=DEFAULT_SCHEME, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
super(OpenMapQuest, self).__init__(format_string, scheme, timeout, proxies, user_agent=user_agent) self.api_key = (api_key or '') self.api = ('%s://open.mapquestapi.com/nominatim/v1/search?format=json' % self.scheme)
'Geocode a location query. :param string 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. .. versionadded:: 0.97'
def geocode(self, query, exactly_one=True, timeout=None):
params = {'q': (self.format_string % query)} if exactly_one: params['maxResults'] = 1 url = '&'.join((self.api, urlencode(params))) logger.debug('%s.geocode: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Parse display name, latitude, and longitude from an JSON response.'
@classmethod def _parse_json(cls, resources, exactly_one=True):
if (not len(resources)): return None if exactly_one: return cls.parse_resource(resources[0]) else: return [cls.parse_resource(resource) for resource in resources]
'Return location and coordinates tuple from dict.'
@classmethod def parse_resource(cls, resource):
location = resource['display_name'] latitude = (resource['lat'] or None) longitude = (resource['lon'] or None) if (latitude and longitude): latitude = float(latitude) longitude = float(longitude) return Location(location, (latitude, longitude), resource)
'Mostly-common geocoder validation, proxies, &c. Not all geocoders specify format_string and such.'
def __init__(self, format_string=DEFAULT_FORMAT_STRING, scheme=DEFAULT_SCHEME, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
self.format_string = format_string self.scheme = scheme if (self.scheme not in ('http', 'https')): raise ConfigurationError('Supported schemes are `http` and `https`.') self.proxies = proxies self.timeout = timeout self.headers = {'User-Agent': (user_agent or DEFAULT_USER_AGENT)} if self.proxies: install_opener(build_opener(ProxyHandler(self.proxies))) self.urlopen = urllib_urlopen
'Do the right thing on "point" input. For geocoders with reverse methods.'
@staticmethod def _coerce_point_to_string(point):
if isinstance(point, Point): return ','.join((str(point.latitude), str(point.longitude))) elif isinstance(point, (list, tuple)): return ','.join((str(point[0]), str(point[1]))) elif isinstance(point, string_compare): return point else: raise ValueError('Invalid point')
'Template for subclasses'
def _parse_json(self, page, exactly_one):
raise NotImplementedError()
'For a generated query URL, get the results.'
def _call_geocoder(self, url, timeout=None, raw=False, requester=None, deserializer=json.loads, **kwargs):
requester = (requester or self.urlopen) if (not requester): req = Request(url=url, headers=self.headers) else: req = url try: page = requester(req, timeout=(timeout or self.timeout), **kwargs) except Exception as error: message = (str(error) if (not py3k) else (str(error.args[0]) if len(error.args) else str(error))) if hasattr(self, '_geocoder_exception_handler'): self._geocoder_exception_handler(error, message) if isinstance(error, HTTPError): code = error.getcode() try: raise ERROR_CODE_MAP[code](message) except KeyError: raise GeocoderServiceError(message) elif isinstance(error, URLError): if ('timed out' in message): raise GeocoderTimedOut('Service timed out') elif ('unreachable' in message): raise GeocoderUnavailable('Service not available') elif isinstance(error, SocketTimeout): raise GeocoderTimedOut('Service timed out') elif isinstance(error, SSLError): if ('timed out' in message): raise GeocoderTimedOut('Service timed out') raise GeocoderServiceError(message) if hasattr(page, 'getcode'): status_code = page.getcode() elif hasattr(page, 'status_code'): status_code = page.status_code else: status_code = None if (status_code in ERROR_CODE_MAP): raise ERROR_CODE_MAP[page.status_code](('\n%s' % decode_page(page))) if raw: return page page = decode_page(page) if (deserializer is not None): try: return deserializer(page) except ValueError: raise GeocoderParseError(('Could not deserialize using deserializer:\n%s' % page)) else: return page
'Implemented in subclasses.'
def geocode(self, query, exactly_one=True, timeout=None):
raise NotImplementedError()
'Implemented in subclasses.'
def reverse(self, query, exactly_one=True, timeout=None):
raise NotImplementedError()
'Create a Yandex-based geocoder. .. versionadded:: 1.5.0 :param string api_key: Yandex API key (not obligatory) http://api.yandex.ru/maps/form.xml :param string lang: response locale, the following locales are supported: "ru_RU" (default), "uk_UA", "be_BY", "en_US", "tr_TR" :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`.'
def __init__(self, api_key=None, lang=None, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
super(Yandex, self).__init__(scheme='http', timeout=timeout, proxies=proxies, user_agent=user_agent) self.api_key = api_key self.lang = lang self.api = 'http://geocode-maps.yandex.ru/1.x/'
'Geocode a location query. :param string 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.'
def geocode(self, query, exactly_one=True, timeout=None):
params = {'geocode': query, 'format': 'json'} if (not (self.api_key is None)): params['key'] = self.api_key if (not (self.lang is None)): params['lang'] = self.lang if (exactly_one is True): params['results'] = 1 url = '?'.join((self.api, urlencode(params))) logger.debug('%s.geocode: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Given a point, find an address. :param string 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 boolean 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.'
def reverse(self, query, exactly_one=False, timeout=None):
try: (lat, lng) = [x.strip() for x in self._coerce_point_to_string(query).split(',')] except ValueError: raise ValueError('Must be a coordinate pair or Point') params = {'geocode': '{0},{1}'.format(lng, lat), 'format': 'json'} if (self.api_key is not None): params['key'] = self.api_key if (self.lang is not None): params['lang'] = self.lang url = '?'.join((self.api, urlencode(params))) logger.debug('%s.reverse: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Parse JSON response body.'
def _parse_json(self, doc, exactly_one):
if doc.get('error'): raise GeocoderServiceError(doc['error']['message']) try: places = doc['response']['GeoObjectCollection']['featureMember'] except KeyError: raise GeocoderParseError('Failed to parse server response') def parse_code(place): '\n Parse each record.\n ' try: place = place['GeoObject'] except KeyError: raise GeocoderParseError('Failed to parse server response') (longitude, latitude) = [float(_) for _ in place['Point']['pos'].split(' ')] location = place.get('description') return Location(location, (latitude, longitude), place) if exactly_one: try: return parse_code(places[0]) except IndexError: return None else: return [parse_code(place) for place in places]
':param string country_bias: :param string username: :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. .. versionadded:: 0.97 :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`. .. versionadded:: 0.96'
def __init__(self, country_bias=None, username=None, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
super(GeoNames, self).__init__(scheme='http', timeout=timeout, proxies=proxies, user_agent=user_agent) if (username == None): raise ConfigurationError('No username given, required for api access. If you do not have a GeoNames username, sign up here: http://www.geonames.org/login') self.username = username self.country_bias = country_bias self.api = ('%s://api.geonames.org/searchJSON' % self.scheme) self.api_reverse = ('%s://api.geonames.org/findNearbyPlaceNameJSON' % self.scheme)
'Geocode a location query. :param string 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. .. versionadded:: 0.97'
def geocode(self, query, exactly_one=True, timeout=None):
params = {'q': query, 'username': self.username} if self.country_bias: params['countryBias'] = self.country_bias if (exactly_one is True): params['maxRows'] = 1 url = '?'.join((self.api, urlencode(params))) logger.debug('%s.geocode: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Given a point, find an address. .. versionadded:: 1.2.0 :param string 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 boolean 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.'
def reverse(self, query, exactly_one=False, timeout=None):
try: (lat, lng) = [x.strip() for x in 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_reverse, urlencode(params))) logger.debug('%s.reverse: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Parse JSON response body.'
def _parse_json(self, doc, exactly_one):
places = doc.get('geonames', []) err = doc.get('status', None) if (err and ('message' in err)): if err['message'].startswith('user account not enabled to use'): raise GeocoderInsufficientPrivileges(err['message']) else: raise GeocoderServiceError(err['message']) if (not len(places)): return None def parse_code(place): '\n Parse each record.\n ' 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('adminCode1', None) country = place.get('countryCode', 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]
'Create a ArcGIS-based geocoder. .. versionadded:: 0.97 :param string username: ArcGIS username. Required if authenticated mode is desired. :param string password: ArcGIS password. Required if authenticated mode is desired. :param string referer: Required if authenticated mode is desired. \'Referer\' HTTP header to send with each request, e.g., \'http://www.example.com\'. This is tied to an issued token, so fielding queries for multiple referrers should be handled by having multiple ArcGIS geocoder instances. :param int token_lifetime: Desired lifetime, in minutes, of an ArcGIS-issued token. :param string scheme: Desired scheme. If authenticated mode is in use, it must be \'https\'. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`.'
def __init__(self, username=None, password=None, referer=None, token_lifetime=60, scheme=DEFAULT_SCHEME, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
super(ArcGIS, self).__init__(scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent) if (username or password or referer): if (not (username and password and referer)): raise ConfigurationError('Authenticated mode requires username, password, and referer') if (self.scheme != 'https'): raise ConfigurationError("Authenticated mode requires scheme of 'https'") self._base_call_geocoder = self._call_geocoder self._call_geocoder = self._authenticated_call_geocoder self.username = username self.password = password self.referer = referer self.token = None self.token_lifetime = (token_lifetime * 60) self.token_expiry = None self.retry = 1 self.api = ('%s://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/find' % self.scheme) self.reverse_api = ('%s://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode' % self.scheme)
'Wrap self._call_geocoder, handling tokens.'
def _authenticated_call_geocoder(self, url, timeout=None):
if ((self.token is None) or (int(time()) > self.token_expiry)): self._refresh_authentication_token() request = Request('&token='.join((url, self.token)), headers={'Referer': self.referer}) return self._base_call_geocoder(request, timeout=timeout)
'Geocode a location query. :param string 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.'
def geocode(self, query, exactly_one=True, timeout=None):
params = {'text': query, 'f': 'json'} if (exactly_one is True): params['maxLocations'] = 1 url = '?'.join((self.api, urlencode(params))) logger.debug('%s.geocode: %s', self.__class__.__name__, url) response = self._call_geocoder(url, timeout=timeout) if ('error' in response): if (response['error']['code'] == self._TOKEN_EXPIRED): self.retry += 1 self._refresh_authentication_token() return self.geocode(query, exactly_one=exactly_one, timeout=timeout) raise GeocoderServiceError(str(response['error'])) if (not len(response['locations'])): return None geocoded = [] for resource in response['locations']: geometry = resource['feature']['geometry'] geocoded.append(Location(resource['name'], (geometry['y'], geometry['x']), resource)) if (exactly_one is True): return geocoded[0] return geocoded
'Given a point, find an address. :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? :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 int distance: Distance from the query location, in meters, within which to search. ArcGIS has a default of 100 meters, if not specified. :param string wkid: WKID to use for both input and output coordinates.'
def reverse(self, query, exactly_one=True, timeout=None, distance=None, wkid=DEFAULT_WKID):
point = self._coerce_point_to_string(query).split(',') if (wkid != DEFAULT_WKID): location = {'x': point[1], 'y': point[0], 'spatialReference': wkid} else: location = ','.join((point[1], point[0])) params = {'location': location, 'f': 'json', 'outSR': wkid} if (distance is not None): params['distance'] = distance url = '?'.join((self.reverse_api, urlencode(params))) logger.debug('%s.reverse: %s', self.__class__.__name__, url) response = self._call_geocoder(url, timeout=timeout) if (not len(response)): return None if ('error' in response): if (response['error']['code'] == self._TOKEN_EXPIRED): self.retry += 1 self._refresh_authentication_token() return self.reverse(query, exactly_one=exactly_one, timeout=timeout, distance=distance, wkid=wkid) raise GeocoderServiceError(str(response['error'])) address = ('%(Address)s, %(City)s, %(Region)s %(Postal)s, %(CountryCode)s' % response['address']) return Location(address, (response['location']['y'], response['location']['x']), response['address'])
'POST to ArcGIS requesting a new token.'
def _refresh_authentication_token(self):
if (self.retry == self._MAX_RETRIES): raise GeocoderAuthenticationFailure(('Too many retries for auth: %s' % self.retry)) token_request_arguments = {'username': self.username, 'password': self.password, 'expiration': self.token_lifetime, 'f': 'json'} token_request_arguments = '&'.join([('%s=%s' % (key, val)) for (key, val) in token_request_arguments.items()]) url = '&'.join(('?'.join((self.auth_api, token_request_arguments)), urlencode({'referer': self.referer}))) logger.debug('%s._refresh_authentication_token: %s', self.__class__.__name__, url) self.token_expiry = (int(time()) + self.token_lifetime) response = self._base_call_geocoder(url) if (not ('token' in response)): raise GeocoderAuthenticationFailure(('Missing token in auth request.Request URL: %s; response JSON: %s' % (url, json.dumps(response)))) self.retry = 0 self.token = response['token']
'Initialize a Photon/Komoot geocoder which aims to let you "search as you type with OpenStreetMap". No API Key is needed by this platform. :param string format_string: String containing \'%s\' where the string to geocode should be interpolated before querying the geocoder. For example: \'%s, Mountain View, CA\'. The default is just \'%s\'. :param string scheme: Use \'https\' or \'http\' as the API URL\'s scheme. Default is https. Note that SSL connections\' certificates are not verified. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`. :param string domain: Should be the localized Photon domain to connect to. The default is \'photon.komoot.de\', but you can change it to a domain of your own.'
def __init__(self, format_string=DEFAULT_FORMAT_STRING, scheme=DEFAULT_SCHEME, timeout=DEFAULT_TIMEOUT, proxies=None, domain='photon.komoot.de'):
super(Photon, self).__init__(format_string, scheme, timeout, proxies) self.domain = domain.strip('/') self.api = ('%s://%s/api' % (self.scheme, self.domain)) self.reverse_api = ('%s://%s/reverse' % (self.scheme, self.domain))
'Geocode a location query. :param string 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 location_bias: The coordinates to used as location bias. :type query: :class:`geopy.point.Point`, list or tuple of (latitude, longitude), or string as "%(latitude)s, %(longitude)s" :param string language: Preferred language in which to return results. :param int limit: Limit the number of returned results, defaults to no limit. :param osm_tag: The expression to filter (include/exclude) by key and/ or value, str as \'key:value\' or list/set of str if multiple filters are requiered as [\'key:!val\', \'!key\', \':!value\']'
def geocode(self, query, exactly_one=True, timeout=None, location_bias=None, language=False, limit=None, osm_tag=None):
params = {'q': (self.format_string % query)} if exactly_one: params['limit'] = 1 if limit: params['limit'] = int(limit) if language: params['lang'] = language if location_bias: try: (lat, lon) = [x.strip() for x in self._coerce_point_to_string(location_bias).split(',')] params['lon'] = lon params['lat'] = lat except ValueError: raise ValueError('Location bias must be a coordinate pair or Point') if osm_tag: if isinstance(osm_tag, string_compare): params['osm_tag'] = [osm_tag] else: if (not (isinstance(osm_tag, list) or isinstance(osm_tag, set))): raise ValueError('osm_tag must be a string expression or a set/list of string expressions') params['osm_tag'] = osm_tag url = '?'.join((self.api, urlencode(params, doseq=True))) logger.debug('%s.geocode: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Returns a reverse geocoded location. :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 string language: Preferred language in which to return results. :param osm_tag: The expression to filter (include/exclude) by key and/ or value, str as \'key:value\' or list/set of str if multiple filters are requiered as [\'key:!val\', \'!key\', \':!value\']'
def reverse(self, query, exactly_one=True, timeout=None, language=False, osm_tag=None):
try: (lat, lon) = [x.strip() for x in self._coerce_point_to_string(query).split(',')] except ValueError: raise ValueError('Must be a coordinate pair or Point') params = {'lat': lat, 'lon': lon} if exactly_one: params['limit'] = 1 if language: params['lang'] = language if osm_tag: if isinstance(osm_tag, string_compare): params['osm_tag'] = osm_tag else: try: params['osm_tag'] = '&osm_tag='.join(osm_tag) except ValueError: raise ValueError('osm_tag must be a string expression or a set/list of string expressions') url = '?'.join((self.reverse_api, urlencode(params))) logger.debug('%s.reverse: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Parse display name, latitude, and longitude from a JSON response.'
@classmethod def _parse_json(cls, resources, exactly_one=True):
if (not len(resources)): return None if exactly_one: return cls.parse_resource(resources['features'][0]) else: return [cls.parse_resource(resource) for resource in resources['features']]
'Return location and coordinates tuple from dict.'
@classmethod def parse_resource(cls, resource):
name_elements = ['name', 'housenumber', 'street', 'postcode', 'street', 'city', 'state', 'country'] name = [resource.get(k) for k in name_elements if resource.get(k)] location = ', '.join(name) latitude = (resource['geometry']['coordinates'][1] or None) longitude = (resource['geometry']['coordinates'][0] or None) if (latitude and longitude): latitude = float(latitude) longitude = float(longitude) return Location(location, (latitude, longitude), resource)
'Initialize a customized IGN France geocoder. :param string api_key: The API key required by IGN France API to perform geocoding requests. You can get your key here: http://api.ign.fr. Mandatory. For authentication with referer and with username/password, the api key always differ. :param string username: When making a call need HTTP simple authentication username. Mandatory if no referer set :param string password: When making a call need HTTP simple authentication password. Mandatory if no referer set :param string referer: When making a call need HTTP referer. Mandatory if no password and username :param string domain: Currently it is \'wxs.ign.fr\', can be changed for testing purposes for developer API e.g gpp3-wxs.ign.fr at the moment. :param string scheme: Use \'https\' or \'http\' as the API URL\'s scheme. Default is https. Note that SSL connections\' certificates are not verified. :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 dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`.'
def __init__(self, api_key, username=None, password=None, referer=None, domain='wxs.ign.fr', scheme=DEFAULT_SCHEME, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
super(IGNFrance, self).__init__(scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent) if ((not (api_key and username and password)) and (not (api_key and referer))): raise ConfigurationError('You should provide an api key and a username with a password or an api key with a referer depending on created api key') if ((username and password) and referer): raise ConfigurationError("You can't set username/password and referer together. The API key always differs depending on both scenarios") if (username and (not password)): raise ConfigurationError('username and password must be set together') self.api_key = api_key self.username = username self.password = password self.referer = referer self.domain = domain.strip('/') self.api = '{scheme}://{domain}/{api_key}/geoportail/ols'.format(scheme=self.scheme, api_key=self.api_key, domain=self.domain) if (username and password and (referer is None)): self.addSimpleHTTPAuthHeader()
'Geocode a location query. :param string query: The query string to be geocoded. :param string query_type: The type to provide for geocoding. It can be PositionOfInterest, StreetAddress or CadastralParcel. StreetAddress is the default choice if none provided. :param int maximum_responses: The maximum number of responses to ask to the API in the query body. :param string is_freeform: Set if return is structured with freeform structure or a more structured returned. By default, value is False. :param string filtering: Provide string that help setting geocoder filter. It contains an XML string. See examples in documentation and ignfrance.py file in directory tests. :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.'
def geocode(self, query, query_type='StreetAddress', maximum_responses=25, is_freeform=False, filtering=None, exactly_one=True, timeout=None):
if (query_type not in ['PositionOfInterest', 'StreetAddress', 'CadastralParcel']): raise GeocoderQueryError("You did not provided a query_type the\n webservice can consume. It should be PositionOfInterest,\n 'StreetAddress or CadastralParcel") if ((query_type == 'CadastralParcel') and (len(query.strip()) != 14)): raise GeocoderQueryError('You must send a string of fourteen\n characters long to match the cadastre required code') sub_request = '\n <GeocodeRequest returnFreeForm="{is_freeform}">\n <Address countryCode="{query_type}">\n <freeFormAddress>{query}</freeFormAddress>\n {filtering}\n </Address>\n </GeocodeRequest>\n ' xml_request = self.xml_request.format(method_name='LocationUtilityService', sub_request=sub_request, maximum_responses=maximum_responses) if is_freeform: is_freeform = 'true' else: is_freeform = 'false' if (filtering is None): filtering = '' request_string = xml_request.format(is_freeform=is_freeform, query=query, query_type=query_type, filtering=filtering) params = {'xls': request_string} url = '?'.join((self.api, urlencode(params))) logger.debug('%s.geocode: %s', self.__class__.__name__, url) raw_xml = self._request_raw_content(url, timeout) return self._parse_xml(raw_xml, is_freeform=is_freeform, exactly_one=exactly_one)
'Given a point, find an address. :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 list reverse_geocode_preference: Enable to set expected results type. It can be StreetAddress or PositionOfInterest. Default is set to StreetAddress :param int maximum_responses: The maximum number of responses to ask to the API in the query body. :param string filtering: Provide string that help setting geocoder filter. It contains an XML string. See examples in documentation and ignfrance.py file in directory tests. :param boolean 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.'
def reverse(self, query, reverse_geocode_preference=('StreetAddress',), maximum_responses=25, filtering='', exactly_one=False, timeout=None):
sub_request = '\n <ReverseGeocodeRequest>\n {reverse_geocode_preference}\n <Position>\n <gml:Point>\n <gml:pos>{query}</gml:pos>\n </gml:Point>\n {filtering}\n </Position>\n </ReverseGeocodeRequest>\n ' xml_request = self.xml_request.format(method_name='ReverseGeocodeRequest', sub_request=sub_request, maximum_responses=maximum_responses) for pref in reverse_geocode_preference: if (pref not in ('StreetAddress', 'PositionOfInterest')): raise GeocoderQueryError('`reverse_geocode_preference` must contain one or more of: StreetAddress, PositionOfInterest') point = self._coerce_point_to_string(query).replace(',', ' ') reverse_geocode_preference = '\n'.join((('<ReverseGeocodePreference>%s</ReverseGeocodePreference>' % pref) for pref in reverse_geocode_preference)) request_string = xml_request.format(maximum_responses=maximum_responses, query=point, reverse_geocode_preference=reverse_geocode_preference, filtering=filtering) url = '?'.join((self.api, urlencode({'xls': request_string}))) logger.debug('%s.reverse: %s', self.__class__.__name__, url) raw_xml = self._request_raw_content(url, timeout) return self._parse_xml(raw_xml, exactly_one=exactly_one, is_reverse=True, is_freeform='false')
'Create Urllib request object embedding HTTP simple authentication'
def addSimpleHTTPAuthHeader(self):
sub_request = '\n <GeocodeRequest returnFreeForm="{is_freeform}">\n <Address countryCode="{query_type}">\n <freeFormAddress>{query}</freeFormAddress>\n </Address>\n </GeocodeRequest>\n ' xml_request = self.xml_request.format(method_name='LocationUtilityService', sub_request=sub_request, maximum_responses=1) request_string = xml_request.format(is_freeform='false', query='rennes', query_type='PositionOfInterest') params = {'xls': request_string} top_level_url = '?'.join((self.api, urlencode(params))) password_mgr = HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, top_level_url, self.username, self.password) handler = HTTPBasicAuthHandler(password_mgr) opener = build_opener(handler) install_opener(opener)
'Returns location, (latitude, longitude) from XML feed and transform to json'
def _parse_xml(self, page, is_reverse=False, is_freeform=False, exactly_one=True):
tree = ET.fromstring(page.encode('utf-8')) def remove_namespace(doc, namespace): 'Remove namespace in the document in place.' ns = ('{%s}' % namespace) ns = u(ns) nsl = len(ns) for elem in doc.getiterator(): if elem.tag.startswith(ns): elem.tag = elem.tag[nsl:] remove_namespace(tree, 'http://www.opengis.net/gml') remove_namespace(tree, 'http://www.opengis.net/xls') remove_namespace(tree, 'http://www.opengis.net/xlsext') places = self._xml_to_json_places(tree, is_reverse=is_reverse) if exactly_one: return self._parse_place(places[0], is_freeform=is_freeform) else: return [self._parse_place(place, is_freeform=is_freeform) for place in places]
'Transform the xml ElementTree due to XML webservice return to json'
@staticmethod def _xml_to_json_places(tree, is_reverse=False):
select_multi = ('GeocodedAddress' if (not is_reverse) else 'ReverseGeocodedLocation') adresses = tree.findall(('.//' + select_multi)) places = [] sel_pl = './/Address/Place[@type="{}"]' for adr in adresses: el = {} el['pos'] = adr.find('./Point/pos') el['street'] = adr.find('.//Address/StreetAddress/Street') el['freeformaddress'] = adr.find('.//Address/freeFormAddress') el['municipality'] = adr.find(sel_pl.format('Municipality')) el['numero'] = adr.find(sel_pl.format('Numero')) el['feuille'] = adr.find(sel_pl.format('Feuille')) el['section'] = adr.find(sel_pl.format('Section')) el['departement'] = adr.find(sel_pl.format('Departement')) el['commune_absorbee'] = adr.find(sel_pl.format('CommuneAbsorbee')) el['commune'] = adr.find(sel_pl.format('Commune')) el['insee'] = adr.find(sel_pl.format('INSEE')) el['qualite'] = adr.find(sel_pl.format('Qualite')) el['territoire'] = adr.find(sel_pl.format('Territoire')) el['id'] = adr.find(sel_pl.format('ID')) el['id_tr'] = adr.find(sel_pl.format('ID_TR')) el['bbox'] = adr.find(sel_pl.format('Bbox')) el['nature'] = adr.find(sel_pl.format('Nature')) el['postal_code'] = adr.find('.//Address/PostalCode') el['extended_geocode_match_code'] = adr.find('.//ExtendedGeocodeMatchCode') place = {} def testContentAttrib(selector, key): '\n Helper to select by attribute and if not attribute,\n value set to empty string\n ' return (selector.attrib.get(key, None) if (selector is not None) else None) place['accuracy'] = testContentAttrib(adr.find('.//GeocodeMatchCode'), 'accuracy') place['match_type'] = testContentAttrib(adr.find('.//GeocodeMatchCode'), 'matchType') place['building'] = testContentAttrib(adr.find('.//Address/StreetAddress/Building'), 'number') place['search_centre_distance'] = testContentAttrib(adr.find('.//SearchCentreDistance'), 'value') for (key, value) in iteritems(el): if (value is not None): place[key] = value.text if (value.text == None): place[key] = None else: place[key] = None if place['pos']: (lat, lng) = place['pos'].split(' ') place['lat'] = lat.strip() place['lng'] = lng.strip() else: place['lat'] = place['lng'] = None place.pop('pos', None) places.append(place) return places
'Send the request to get raw content.'
def _request_raw_content(self, url, timeout):
request = Request(url) if (self.referer is not None): request.add_header('Referer', self.referer) raw_xml = self._call_geocoder(request, timeout=timeout, deserializer=None) return raw_xml
'Get the location, lat, lng and place from a single json place.'
@staticmethod def _parse_place(place, is_freeform=None):
if (is_freeform == 'true'): location = place.get('freeformaddress') elif place.get('numero'): location = place.get('street') else: location = ('%s %s' % (place.get('postal_code', ''), place.get('commune', ''))) if place.get('street'): location = ('%s, %s' % (place.get('street', ''), location)) if place.get('building'): location = ('%s %s' % (place.get('building', ''), location)) return Location(location, (place.get('lat'), place.get('lng')), place)
'Create a DataBC-based geocoder. :param string scheme: Desired scheme. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`.'
def __init__(self, scheme=DEFAULT_SCHEME, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
super(DataBC, self).__init__(scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent) self.api = ('%s://apps.gov.bc.ca/pub/geocoder/addresses.geojson' % self.scheme)
'Geocode a location query. :param string query: The address or query you wish to geocode. :param int max_results: The maximum number of resutls to request. :param float set_back: The distance to move the accessPoint away from the curb (in meters) and towards the interior of the parcel. location_descriptor must be set to accessPoint for set_back to take effect. :param string location_descriptor: The type of point requested. It can be any, accessPoint, frontDoorPoint, parcelPoint, rooftopPoint and routingPoint. :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.'
def geocode(self, query, max_results=25, set_back=0, location_descriptor='any', exactly_one=True, timeout=None):
params = {'addressString': query} if (set_back != 0): params['setBack'] = set_back if (location_descriptor not in ['any', 'accessPoint', 'frontDoorPoint', 'parcelPoint', 'rooftopPoint', 'routingPoint']): raise GeocoderQueryError('You did not provided a location_descriptor the webservice can consume. It should be any, accessPoint, frontDoorPoint, parcelPoint, rooftopPoint or routingPoint.') params['locationDescriptor'] = location_descriptor if (exactly_one is True): max_results = 1 params['maxResults'] = max_results url = '?'.join((self.api, urlencode(params))) logger.debug('%s.geocode: %s', self.__class__.__name__, url) response = self._call_geocoder(url, timeout=timeout) if (not len(response['features'])): return None geocoded = [] for feature in response['features']: geocoded.append(self._parse_feature(feature)) if (exactly_one is True): return geocoded[0] return geocoded
'Initialize a What3Words geocoder with 3-word or OneWord-address and What3Words API key. .. versionadded:: 1.5.0 :param string api_key: Key provided by What3Words. :param string format_string: String containing \'%s\' where the string to geocode should be interpolated before querying the geocoder. For example: \'%s, piped.gains.jungle\'. The default is just \'%s\'. :param string scheme: Use \'https\' or \'http\' as the API URL\'s scheme. Default is https. Note that SSL connections\' certificates are not verified. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`.'
def __init__(self, api_key, format_string=DEFAULT_FORMAT_STRING, scheme=DEFAULT_SCHEME, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
super(What3Words, self).__init__(format_string, scheme, timeout, proxies, user_agent=user_agent) self.api_key = api_key self.api = ('%s://api.what3words.com/' % self.scheme)
'Check query validity with regex'
def _check_query(self, query):
if (not (self.word_re.match(query) or self.multiple_word_re.match(query))): return False else: return True
'Geocode a "3 words" or "OneWord" query. :param string query: The 3-word or OneWord-address you wish to geocode. :param string lang: two character language codes as supported by the API (http://what3words.com/api/reference/languages). :param bool exactly_one: Parameter has no effect for this geocoder. Due to the address scheme there is always exactly one result. :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. .. versionadded:: 0.97'
def geocode(self, query, lang='en', exactly_one=True, timeout=None):
if (not self._check_query(query)): raise exc.GeocoderQueryError("Search string must be either like 'word.word.word' or '*word' ") params = {'string': (self.format_string % query), 'lang': (self.format_string % lang.lower())} url = '?'.join(((self.api + 'w3w'), '&'.join(('='.join(('key', self.api_key)), urlencode(params))))) logger.debug('%s.geocode: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Parse type, words, latitude, and longitude and language from a JSON response.'
def _parse_json(self, resources, exactly_one=True):
if (resources.get('error') == 'X1'): raise exc.GeocoderAuthenticationFailure() if (resources.get('error') == '11'): raise exc.GeocoderQueryError('Address (Word(s)) not recognised by What3Words.') def parse_resource(resource): '\n Parse record.\n ' if (resource['type'] == '3 words'): words = resource['words'] words = join_filter('.', [words[0], words[1], words[2]]) position = resource['position'] (latitude, longitude) = (position[0], position[1]) if (latitude and longitude): latitude = float(latitude) longitude = float(longitude) return Location(words, (latitude, longitude), resource) elif (resource['type'] == 'OneWord'): words = resource['words'] words = join_filter('.', [words[0], words[1], words[2]]) oneword = resource['oneword'] info = resource['info'] address = join_filter(', ', [oneword, words, info['name'], info['address1'], info['address2'], info['address3'], info['city'], info['county'], info['postcode'], info['country_id']]) position = resource['position'] (latitude, longitude) = (position[0], position[1]) if (latitude and longitude): latitude = float(latitude) longitude = float(longitude) return Location(address, (latitude, longitude), resource) else: raise exc.GeocoderParseError('Error parsing result.') return parse_resource(resources)
'Given a point, find the 3 word address. :param query: The coordinates for which you wish to obtain the 3 word address. :type query: :class:`geopy.point.Point`, list or tuple of (latitude, longitude), or string as "%(latitude)s, %(longitude)s" :param string lang: two character language codes as supported by the API (http://what3words.com/api/reference/languages). :param bool exactly_one: Parameter has no effect for this geocoder. Due to the address scheme there is always exactly one result. :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.'
def reverse(self, query, lang='en', exactly_one=True, timeout=None):
lang = lang.lower() params = {'position': self._coerce_point_to_string(query), 'lang': (self.format_string % lang)} url = '?'.join(((self.api + 'position'), '&'.join(('='.join(('key', self.api_key)), urlencode(params))))) logger.debug('%s.reverse: %s', self.__class__.__name__, url) return self._parse_reverse_json(self._call_geocoder(url, timeout=timeout))
'Parses a location from a single-result reverse API call.'
@staticmethod def _parse_reverse_json(resources):
if (resources.get('error') == '21'): raise exc.GeocoderQueryError('Invalid coordinates') def parse_resource(resource): '\n Parse resource to return Geopy Location object\n ' words = resource['words'] words = join_filter('.', [words[0], words[1], words[2]]) position = resource['position'] (latitude, longitude) = (position[0], position[1]) if (latitude and longitude): latitude = float(latitude) longitude = float(longitude) return Location(words, (latitude, longitude), resource) return parse_resource(resources)
'Create a geocoder for GeocodeFarm. .. versionadded:: 0.99 :param string api_key: The API key required by GeocodeFarm to perform geocoding requests. :param string format_string: String containing \'%s\' where the string to geocode should be interpolated before querying the geocoder. For example: \'%s, Mountain View, CA\'. The default is just \'%s\'. :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`.'
def __init__(self, api_key=None, format_string=DEFAULT_FORMAT_STRING, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
super(GeocodeFarm, self).__init__(format_string, 'https', timeout, proxies, user_agent=user_agent) self.api_key = api_key self.format_string = format_string self.api = ('%s://www.geocode.farm/v3/json/forward/' % self.scheme) self.reverse_api = ('%s://www.geocode.farm/v3/json/reverse/' % self.scheme)
'Geocode a location query. :param string 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.'
def geocode(self, query, exactly_one=True, timeout=None):
params = {'addr': (self.format_string % query)} if self.api_key: params['key'] = self.api_key url = '?'.join((self.api, urlencode(params))) logger.debug('%s.geocode: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Returns a reverse geocoded location. :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. GeocodeFarm\'s API will always return at most one result. :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.'
def reverse(self, query, exactly_one=True, timeout=None):
try: (lat, lon) = [x.strip() for x in self._coerce_point_to_string(query).split(',')] except ValueError: raise ValueError('Must be a coordinate pair or Point') params = {'lat': lat, 'lon': lon} if self.api_key: params['key'] = self.api_key url = '?'.join((self.reverse_api, urlencode(params))) logger.debug('%s.reverse: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Parse each resource.'
@staticmethod def parse_code(results):
places = [] for result in results.get('RESULTS'): coordinates = result.get('COORDINATES', {}) address = result.get('ADDRESS', {}) latitude = coordinates.get('latitude', None) longitude = coordinates.get('longitude', None) placename = address.get('address_returned', None) if (placename is None): placename = address.get('address', None) if (latitude and longitude): latitude = float(latitude) longitude = float(longitude) places.append(Location(placename, (latitude, longitude), result)) return places
'Raise any exceptions if there were problems reported in the api response.'
@staticmethod def _check_for_api_errors(geocoding_results):
status_result = geocoding_results.get('STATUS', {}) api_call_success = (status_result.get('status', '') == 'SUCCESS') if (not api_call_success): access_error = status_result.get('access') access_error_to_exception = {'API_KEY_INVALID': GeocoderAuthenticationFailure, 'OVER_QUERY_LIMIT': GeocoderQuotaExceeded} exception_cls = access_error_to_exception.get(access_error, GeocoderServiceError) raise exception_cls(access_error)
'Initialize a customized Bing geocoder with location-specific address information and your Bing Maps API key. :param string api_key: Should be a valid Bing Maps API key. :param string format_string: String containing \'%s\' where the string to geocode should be interpolated before querying the geocoder. For example: \'%s, Mountain View, CA\'. The default is just \'%s\'. :param string scheme: Use \'https\' or \'http\' as the API URL\'s scheme. Default is https. Note that SSL connections\' certificates are not verified. .. versionadded:: 0.97 :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. .. versionadded:: 0.97 :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`. .. versionadded:: 0.96'
def __init__(self, api_key, format_string=DEFAULT_FORMAT_STRING, scheme=DEFAULT_SCHEME, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
super(Bing, self).__init__(format_string, scheme, timeout, proxies, user_agent=user_agent) self.api_key = api_key self.api = ('%s://dev.virtualearth.net/REST/v1/Locations' % self.scheme)
'Geocode an address. :param string query: The address or query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `addressLine`, `locality` (city), `adminDistrict` (state), `countryRegion`, or `postalcode`. :param bool exactly_one: Return one result or a list of results, if available. :param user_location: Prioritize results closer to this location. .. versionadded:: 0.96 :type user_location: :class:`geopy.point.Point` :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. .. versionadded:: 0.97 :param string culture: Affects the language of the response, must be a two-letter country code. .. versionadded:: 1.4.0 :param boolean include_neighborhood: Sets whether to include the neighborhood field in the response. .. versionadded:: 1.4.0 :param boolean include_country_code: Sets whether to include the two-letter ISO code of the country in the response (field name \'countryRegionIso2\'). .. versionadded:: 1.4.0'
def geocode(self, query, exactly_one=True, user_location=None, timeout=None, culture=None, include_neighborhood=None, include_country_code=False):
if isinstance(query, dict): params = {key: val for (key, val) in query.items() if (key in self.structured_query_params)} params['key'] = self.api_key else: params = {'query': (self.format_string % query), 'key': self.api_key} if user_location: params['userLocation'] = ','.join((str(user_location.latitude), str(user_location.longitude))) if (exactly_one is True): params['maxResults'] = 1 if culture: params['culture'] = culture if (include_neighborhood is not None): params['includeNeighborhood'] = include_neighborhood if include_country_code: params['include'] = 'ciso2' url = '?'.join((self.api, urlencode(params))) logger.debug('%s.geocode: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Reverse geocode a 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? :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. .. versionadded:: 0.97'
def reverse(self, query, exactly_one=True, timeout=None):
point = self._coerce_point_to_string(query) params = {'key': self.api_key} url = ('%s/%s?%s' % (self.api, point, urlencode(params))) logger.debug('%s.reverse: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Parse a location name, latitude, and longitude from an JSON response.'
@staticmethod def _parse_json(doc, exactly_one=True):
status_code = doc.get('statusCode', 200) if (status_code != 200): err = doc.get('errorDetails', '') if (status_code == 401): raise GeocoderAuthenticationFailure(err) elif (status_code == 403): raise GeocoderInsufficientPrivileges(err) elif (status_code == 429): raise GeocoderQuotaExceeded(err) elif (status_code == 503): raise GeocoderUnavailable(err) else: raise GeocoderServiceError(err) resources = doc['resourceSets'][0]['resources'] if ((resources is None) or (not len(resources))): return None def parse_resource(resource): '\n Parse each return object.\n ' stripchars = ', \n' addr = resource['address'] address = addr.get('addressLine', '').strip(stripchars) city = addr.get('locality', '').strip(stripchars) state = addr.get('adminDistrict', '').strip(stripchars) zipcode = addr.get('postalCode', '').strip(stripchars) country = addr.get('countryRegion', '').strip(stripchars) city_state = join_filter(', ', [city, state]) place = join_filter(' ', [city_state, zipcode]) location = join_filter(', ', [address, place, country]) latitude = (resource['point']['coordinates'][0] or None) longitude = (resource['point']['coordinates'][1] or None) if (latitude and longitude): latitude = float(latitude) longitude = float(longitude) return Location(location, (latitude, longitude), resource) if exactly_one: return parse_resource(resources[0]) else: return [parse_resource(resource) for resource in resources]
':param string format_string: String containing \'%s\' where the string to geocode should be interpolated before querying the geocoder. For example: \'%s, Mountain View, CA\'. The default is just \'%s\'. :param tuple view_box: Coordinates to restrict search within. :param string country_bias: Bias results to this country. :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`. .. versionadded:: 0.96 :param string domain: Should be the localized Openstreetmap domain to connect to. The default is \'nominatim.openstreetmap.org\', but you can change it to a domain of your own. .. versionadded:: 1.8.2 :param string scheme: Use \'https\' or \'http\' as the API URL\'s scheme. Default is https. Note that SSL connections\' certificates are not verified. .. versionadded:: 1.8.2'
def __init__(self, format_string=DEFAULT_FORMAT_STRING, view_box=None, country_bias=None, timeout=DEFAULT_TIMEOUT, proxies=None, domain='nominatim.openstreetmap.org', scheme=DEFAULT_SCHEME, user_agent=None):
super(Nominatim, self).__init__(format_string, scheme, timeout, proxies, user_agent=user_agent) self.country_bias = country_bias self.format_string = format_string self.view_box = view_box self.domain = domain.strip('/') self.api = ('%s://%s/search' % (self.scheme, self.domain)) self.reverse_api = ('%s://%s/reverse' % (self.scheme, self.domain))
'Geocode a location query. :param query: The address, query or structured query to geocode you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `street`, `city`, `county`, `state`, `country`, or `postalcode`. For more information, see Nominatim\'s documentation for "structured requests": https://wiki.openstreetmap.org/wiki/Nominatim :type query: dict or string .. versionchanged:: 1.0.0 :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. .. versionadded:: 0.97 :param addressdetails: If you want in *Location.raw* to include addressdetails such as city_district, etc set it to True :type addressdetails: bool :param string language: Preferred language in which to return results. Either uses standard `RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>`_ accept-language string or a simple comma-separated list of language codes. :type addressdetails: string .. versionadded:: 1.0.0 :param string geometry: If present, specifies whether the geocoding service should return the result\'s geometry in `wkt`, `svg`, `kml`, or `geojson` formats. This is available via the `raw` attribute on the returned :class:`geopy.location.Location` object. .. versionadded:: 1.3.0'
def geocode(self, query, exactly_one=True, timeout=None, addressdetails=False, language=False, geometry=None):
if isinstance(query, dict): params = {key: val for (key, val) in query.items() if (key in self.structured_query_params)} else: params = {'q': (self.format_string % query)} params.update({'format': 'json'}) if self.view_box: params['viewbox'] = ','.join(self.view_box) if self.country_bias: params['countrycodes'] = self.country_bias if addressdetails: params['addressdetails'] = 1 if language: params['accept-language'] = language if (geometry is not None): geometry = geometry.lower() if (geometry == 'wkt'): params['polygon_text'] = 1 elif (geometry == 'svg'): params['polygon_svg'] = 1 elif (geometry == 'kml'): params['polygon_kml'] = 1 elif (geometry == 'geojson'): params['polygon_geojson'] = 1 else: raise GeocoderQueryError('Invalid geometry format. Must be one of: wkt, svg, kml, geojson.') url = '?'.join((self.api, urlencode(params))) logger.debug('%s.geocode: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Returns a reverse geocoded location. :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. .. versionadded:: 0.97 :param string language: Preferred language in which to return results. Either uses standard `RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>`_ accept-language string or a simple comma-separated list of language codes. :type addressdetails: string .. versionadded:: 1.0.0'
def reverse(self, query, exactly_one=True, timeout=None, language=False):
try: (lat, lon) = [x.strip() for x in self._coerce_point_to_string(query).split(',')] except ValueError: raise ValueError('Must be a coordinate pair or Point') params = {'lat': lat, 'lon': lon, 'format': 'json'} if language: params['accept-language'] = language url = '?'.join((self.reverse_api, urlencode(params))) logger.debug('%s.reverse: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Parse each resource.'
@staticmethod def parse_code(place):
latitude = place.get('lat', None) longitude = place.get('lon', None) placename = place.get('display_name', None) if (latitude and longitude): latitude = float(latitude) longitude = float(longitude) return Location(placename, (latitude, longitude), place)
'Initialize a customized Google geocoder. API authentication is only required for Google Maps Premier customers. :param string api_key: The API key required by Google to perform geocoding requests. API keys are managed through the Google APIs console (https://code.google.com/apis/console). .. versionadded:: 0.98.2 :param string domain: Should be the localized Google Maps domain to connect to. The default is \'maps.googleapis.com\', but if you\'re geocoding address in the UK (for example), you may want to set it to \'maps.google.co.uk\' to properly bias results. :param string scheme: Use \'https\' or \'http\' as the API URL\'s scheme. Default is https. Note that SSL connections\' certificates are not verified. .. versionadded:: 0.97 :param string client_id: If using premier, the account client id. :param string secret_key: If using premier, the account secret key. :param string channel: If using premier, the channel identifier. :param dict proxies: If specified, routes this geocoder\'s requests through the specified proxy. E.g., {"https": "192.0.2.0"}. For more information, see documentation on :class:`urllib2.ProxyHandler`. .. versionadded:: 0.96'
def __init__(self, api_key=None, domain='maps.googleapis.com', scheme=DEFAULT_SCHEME, client_id=None, secret_key=None, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None, channel=''):
super(GoogleV3, self).__init__(scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent) if (client_id and (not secret_key)): raise ConfigurationError('Must provide secret_key with client_id.') if (secret_key and (not client_id)): raise ConfigurationError('Must provide client_id with secret_key.') self.api_key = api_key self.domain = domain.strip('/') self.scheme = scheme self.doc = {} self.premier = bool((client_id and secret_key)) self.client_id = client_id self.secret_key = secret_key self.channel = channel self.api = ('%s://%s/maps/api/geocode/json' % (self.scheme, self.domain)) self.tz_api = ('%s://%s/maps/api/timezone/json' % (self.scheme, self.domain))
'Returns a Premier account signed url. Docs on signature: https://developers.google.com/maps/documentation/business/webservices/auth#digital_signatures'
def _get_signed_url(self, params):
params['client'] = self.client_id if self.channel: params['channel'] = self.channel path = '?'.join(('/maps/api/geocode/json', urlencode(params))) signature = hmac.new(base64.urlsafe_b64decode(self.secret_key), path.encode('utf-8'), hashlib.sha1) signature = base64.urlsafe_b64encode(signature.digest()).decode('utf-8') return ('%s://%s%s&signature=%s' % (self.scheme, self.domain, path, signature))
'Format the components dict to something Google understands.'
@staticmethod def _format_components_param(components):
return '|'.join((':'.join(item) for item in components.items()))
'Format the bounds to something Google understands.'
@staticmethod def _format_bounds_param(bounds):
return ('%f,%f|%f,%f' % (bounds[0], bounds[1], bounds[2], bounds[3]))
'Geocode a location query. :param string 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. .. versionadded:: 0.97 :param bounds: The bounding box of the viewport within which to bias geocode results more prominently. :type bounds: list or tuple :param string region: The region code, specified as a ccTLD ("top-level domain") two-character value. :param dict components: Restricts to an area. Can use any combination of: route, locality, administrative_area, postal_code, country. .. versionadded:: 0.97.1 :param string language: The language in which to return results. :param bool sensor: Whether the geocoding request comes from a device with a location sensor.'
def geocode(self, query, exactly_one=True, timeout=None, bounds=None, region=None, components=None, language=None, sensor=False):
params = {'address': (self.format_string % query), 'sensor': str(sensor).lower()} if self.api_key: params['key'] = self.api_key if bounds: if (len(bounds) != 4): raise GeocoderQueryError('bounds must be a four-item iterable of lat,lon,lat,lon') params['bounds'] = self._format_bounds_param(bounds) if region: params['region'] = region if components: params['components'] = self._format_components_param(components) if language: params['language'] = language if (self.premier is False): url = '?'.join((self.api, urlencode(params))) else: url = self._get_signed_url(params) logger.debug('%s.geocode: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'Given a point, find an address. :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 boolean 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. .. versionadded:: 0.97 :param string language: The language in which to return results. :param boolean sensor: Whether the geocoding request comes from a device with a location sensor.'
def reverse(self, query, exactly_one=False, timeout=None, language=None, sensor=False):
params = {'latlng': self._coerce_point_to_string(query), 'sensor': str(sensor).lower()} if language: params['language'] = language if self.api_key: params['key'] = self.api_key if (not self.premier): url = '?'.join((self.api, urlencode(params))) else: url = self._get_signed_url(params) logger.debug('%s.reverse: %s', self.__class__.__name__, url) return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
'**This is an unstable API.** Finds the timezone a `location` was in for a specified `at_time`, and returns a pytz timezone object. .. versionadded:: 1.2.0 :param location: The coordinates for which you want a timezone. :type location: :class:`geopy.point.Point`, list or tuple of (latitude, longitude), or string as "%(latitude)s, %(longitude)s" :param at_time: The time at which you want the timezone of this location. This is optional, and defaults to the time that the function is called in UTC. :type at_time integer, long, float, datetime: :rtype: pytz timezone'
def timezone(self, location, at_time=None, timeout=None):
if (not pytz_available): raise ImportError('pytz must be installed in order to locate timezones. Install with `pip install geopy -e ".[timezone]"`.') location = self._coerce_point_to_string(location) if isinstance(at_time, Number): timestamp = at_time elif isinstance(at_time, datetime): timestamp = timegm(at_time.utctimetuple()) elif (at_time is None): timestamp = timegm(datetime.utcnow().utctimetuple()) else: raise GeocoderQueryError('`at_time` must be an epoch integer or datetime.datetime object') params = {'location': location, 'timestamp': timestamp} if self.api_key: params['key'] = self.api_key url = '?'.join((self.tz_api, urlencode(params))) logger.debug('%s.timezone: %s', self.__class__.__name__, url) response = self._call_geocoder(url, timeout=timeout) try: tz = timezone(response['timeZoneId']) except UnknownTimeZoneError: raise GeocoderParseError(('pytz could not parse the timezone identifier (%s) returned by the service.' % response['timeZoneId'])) except KeyError: raise GeocoderParseError(('geopy could not find a timezone in this response: %s' % response)) return tz
'Returns location, (latitude, longitude) from json feed.'
def _parse_json(self, page, exactly_one=True):
places = page.get('results', []) if (not len(places)): self._check_status(page.get('status')) return None def parse_place(place): 'Get the location, lat, lng from a single json place.' location = place.get('formatted_address') latitude = place['geometry']['location']['lat'] longitude = place['geometry']['location']['lng'] return Location(location, (latitude, longitude), place) if exactly_one: return parse_place(places[0]) else: return [parse_place(place) for place in places]
'Validates error statuses.'
@staticmethod def _check_status(status):
if (status == 'ZERO_RESULTS'): return if (status == 'OVER_QUERY_LIMIT'): raise GeocoderQuotaExceeded('The given key has gone over the requests limit in the 24 hour period or has submitted too many requests in too short a period of time.') elif (status == 'REQUEST_DENIED'): raise GeocoderQueryError('Your request was denied.') elif (status == 'INVALID_REQUEST'): raise GeocoderQueryError('Probably missing address or latlng.') else: raise GeocoderQueryError('Unknown error.')