· 5 years ago · Aug 23, 2020, 09:40 AM
1import requests
2# You need to install the requests module to use this code
3import json
4
5api_key = False
6# If you have a Google Places API key, enter it here
7# api_key = 'AIzaSy___IDByT70'
8# https://developers.google.com/maps/documentation/geocoding/intro
9
10if api_key is False:
11 api_key = 42
12 serviceurl = 'http://py4e-data.dr-chuck.net/json'
13else :
14 serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json'
15
16while True:
17 address = input('Enter location: ')
18 if len(address) < 1: break
19
20 payload = dict()
21 payload['address'] = address
22 if api_key is not False: payload['key'] = api_key
23
24 r = requests.get(serviceurl, params=payload)
25 print('Retrieved', r.url)
26 data = r.text
27 print('Retrieved', len(data), 'characters')
28
29 try:
30 js = json.loads(data)
31 except:
32 js = None
33
34 if not js or 'status' not in js or js['status'] != 'OK':
35 print('==== Failure To Retrieve ====')
36 print(data)
37 continue
38
39 print(json.dumps(js, indent=4))
40
41 lat = js['results'][0]['geometry']['location']['lat']
42 lng = js['results'][0]['geometry']['location']['lng']
43 print('lat', lat, 'lng', lng)
44 location = js['results'][0]['formatted_address']
45 print(location)
46