-
Notifications
You must be signed in to change notification settings - Fork 0
/
geocode_provider_google.py
51 lines (42 loc) · 1.7 KB
/
geocode_provider_google.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import requests
from geocode_exceptions import GeocodeException, GeocodeNotFoundException
from geocode_result import GeocodeResult
class GeocodeProviderGoogle:
"""
This provider uses the Google API to do geocoding.
"""
def __init__(self, credential_store, api_url="https://maps.googleapis.com/maps/api/geocode/json"):
"""
Create a Google geocode provider
:param credential_store: credential store used to app key
:param api_url: The url of the here api
"""
self._credential_store = credential_store
self._api_url = api_url
def resolve(self, query):
"""
Resolves a query into a latitude/longitude
:param query: The query string
:return: The query result
"""
# build the url parameters for the API request
parameters = {
"key": self._credential_store.get("google_api_key"),
"address": query
}
try:
# do the actual request
response = requests.get(self._api_url, params = parameters, timeout=2)
# parse the relevant data from the response
response_json = response.json()
if len(response_json["results"]) == 0:
# no result found
raise GeocodeNotFoundException()
location = response_json["results"][0]["geometry"]["location"]
result = GeocodeResult(location["lat"], location["lng"])
except GeocodeNotFoundException as e:
raise
except Exception as e:
# something went wrong during the request. Let the caller know
raise GeocodeException("Error resolving with Google API", e)
return result