PYCON 60
Geojson.py Guest on 20th July 2020 11:50:41 AM
  1. import urllib.request, urllib.parse, urllib.error
  2. import json
  3. import ssl
  4.  
  5. api_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.  
  10. if api_key is False:
  11.     api_key = 42
  12.     serviceurl = 'http://py4e-data.dr-chuck.net/json?'
  13. else :
  14.     serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?'
  15.  
  16. # Ignore SSL certificate errors
  17. ctx = ssl.create_default_context()
  18. ctx.check_hostname = False
  19. ctx.verify_mode = ssl.CERT_NONE
  20.  
  21. while True:
  22.     address = input('Enter location: ')
  23.     if len(address) < 1: break
  24.  
  25.     parms = dict()
  26.     parms['address'] = address
  27.     if api_key is not False: parms['key'] = api_key
  28.     url = serviceurl + urllib.parse.urlencode(parms)
  29.  
  30.     print('Retrieving', url)
  31.     uh = urllib.request.urlopen(url, context=ctx)
  32.     data = uh.read().decode()
  33.     print('Retrieved', len(data), 'characters')
  34.  
  35.     try:
  36.         js = json.loads(data)
  37.     except:
  38.         js = None
  39.  
  40.     if not js or 'status' not in js or js['status'] != 'OK':
  41.         print('==== Failure To Retrieve ====')
  42.         print(data)
  43.         continue
  44.  
  45.     print(json.dumps(js, indent=4))
  46.  
  47.     lat = js['results'][0]['geometry']['location']['lat']
  48.     lng = js['results'][0]['geometry']['location']['lng']
  49.     print('lat', lat, 'lng', lng)
  50.     location = js['results'][0]['formatted_address']
  51.     print(location)

Paste is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.