forked from Unicaronas/Unicaronas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeocoding.py
61 lines (53 loc) · 1.7 KB
/
geocoding.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import requests
from django.conf import settings
from django.contrib.gis.geos.collections import Point
def extract_data_from_response(data, idx=0):
"""
Given some data, extract the formatted address and the geometry point
"""
if data['status'] != 'OK':
raise ValueError('Given data contains no information')
results = data['results'][idx]
formatted_address = results['formatted_address']
latitude = results['geometry']['location']['lat']
longitude = results['geometry']['location']['lng']
return formatted_address, Point(latitude, longitude)
def geocode_address(address):
"""
Given a typed address, use google's api to fetch
the formatted address and the geometry point
"""
url = "https://maps.googleapis.com/maps/api/geocode/json"
api_key = settings.GEOCODING_API_KEY
payload = {
'address': address,
'key': api_key,
'region': 'br'
}
r = requests.get(url, params=payload)
r.raise_for_status()
data = r.json()
return extract_data_from_response(data)
def reverse_geocode(point):
"""
Given a geometry point, use google's api to fetch
the formatted address and the geometry point
"""
url = "https://maps.googleapis.com/maps/api/geocode/json"
api_key = settings.GEOCODING_API_KEY
payload = {
'latlng': f"{point.coords[0]},{point.coords[1]}",
'key': api_key,
'region': 'br'
}
r = requests.get(url, params=payload)
r.raise_for_status()
data = r.json()
return extract_data_from_response(data)
def map_common_results(address):
"""
Take an address and try to map it to
common, correct, addresses
"""
# Implement this
return address