There are several issues in your code. First of all, urllib
has been split up in Python 3, please check out 'module' has no attribute 'urlencode'.
Secondly, you need to use the HTTPS protocol in the Geocoding request, and make sure that you use a valid API key:
serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?key=AIza****sYjs&'
Thirdly, replace json.loads(str(data))
with just json.loads(data)
.
Full amended code below:
import urllib.parse
import urllib.request
import json
serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?key=AIza****sYjs&'
while True:
address = input('Enter location: ')
if len(address) < 1:
break
url = serviceurl + urllib.parse.urlencode({'sensor': 'false',
'address': address})
print('Retrieving', url)
uh = urllib.request.urlopen(url)
data = uh.read()
print('Retrieved', len(data), 'characters')
try:
js = json.loads(data)
except:
js = None
if 'status' not in js or js['status'] != 'OK':
print('==== Failure To Retrieve ====')
print(data)
continue
print(json.dumps(js, indent=4))
lat = js["results"][0]["geometry"]["location"]["lat"]
lng = js["results"][0]["geometry"]["location"]["lng"]
print('lat', lat, 'lng', lng)
location = js['results'][0]['formatted_address']
print(location)
Output for e.g. "paris,france":
Enter location: paris,france
Retrieving https://maps.googleapis.com/maps/api/geocode/json?key=AIza****sYjs&sensor=false&address=paris%2Cfrance
Retrieved 1690 characters
{
"results": [
{
"address_components": [
{
"long_name": "Paris",
"short_name": "Paris",
"types": [
"locality",
"political"
]
},
{
"long_name": "Paris",
"short_name": "Paris",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "\u00cele-de-France",
"short_name": "IDF",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "France",
"short_name": "FR",
"types": [
"country",
"political"
]
}
],
"formatted_address": "Paris, France",
"geometry": {
"bounds": {
"northeast": {
"lat": 48.9021449,
"lng": 2.4699208
},
"southwest": {
"lat": 48.815573,
"lng": 2.224199
}
},
"location": {
"lat": 48.856614,
"lng": 2.3522219
},
"location_type": "APPROXIMATE",
"viewport": {
"northeast": {
"lat": 48.9021449,
"lng": 2.4699208
},
"southwest": {
"lat": 48.815573,
"lng": 2.224199
}
}
},
"place_id": "ChIJD7fiBh9u5kcRYJSMaMOCCwQ",
"types": [
"locality",
"political"
]
}
],
"status": "OK"
}
lat 48.856614 lng 2.3522219
Paris, France
Hope this helps!