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.assertTr... |
'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 i... | 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... |
'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 serv... | 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.authenticat... |
'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 ... | 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... |
'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', N... |
':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 tu... | 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_ap... |
'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:`g... | 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]
... |
'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 resul... | 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, urlen... |
'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 defau... | 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 ... | 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_... |
'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(er... |
'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... | 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 ... | 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(... |
'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 ... | 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):
para... |
'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 ... |
':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. ... | 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:... |
'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 ... | 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 se... |
'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 ... | 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(param... |
'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['m... |
'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 sen... | 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')
... |
'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 ... | 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):
... |
'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... | 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):... |
'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... |
'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 de... | 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 ... | 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_bia... |
'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 resul... | 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[... |
'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']['coordina... |
'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... | 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 ... |
'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 response... | 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 ... |
'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 res... | 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 ... |
'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 ... |
'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):
... |
'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('... |
'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' % ... |
'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.,... | 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 t... | 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 t... |
'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, pi... | 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 addres... | 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(('=... |
'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 ... |
'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 (ht... | 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._p... |
'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 '
... |
'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... | 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 ... | 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 resul... | 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((se... |
'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)
... |
'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': Geoco... |
'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: \'... | 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
availab... | 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'] = ','.joi... |
'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 timeou... | 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 == ... |
':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 count... | 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... |
'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 reques... | 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.... |
'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 resul... | 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
... |
'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
:par... | 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 p... |
'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(signatur... |
'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 ... | 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... |
'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... | 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_... |
'**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 "%(... | 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 =... |
'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 = pla... |
'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 per... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.