PYCON 54
Geoxml.py Guest on 20th July 2020 11:49:36 AM
  1. import urllib.request, urllib.parse, urllib.error
  2. import xml.etree.ElementTree as ET
  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/xml?'
  13. else :
  14.     serviceurl = 'https://maps.googleapis.com/maps/api/geocode/xml?'
  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.     print('Retrieving', url)
  30.     uh = urllib.request.urlopen(url, context=ctx)
  31.  
  32.     data = uh.read()
  33.     print('Retrieved', len(data), 'characters')
  34.     print(data.decode())
  35.     tree = ET.fromstring(data)
  36.  
  37.     results = tree.findall('result')
  38.     lat = results[0].find('geometry').find('location').find('lat').text
  39.     lng = results[0].find('geometry').find('location').find('lng').text
  40.     location = results[0].find('formatted_address').text
  41.  
  42.     print('lat', lat, 'lng', lng)
  43.     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.