I'm trying to get some basic access to the Google Maps API. In their Geocoding Strategies they have an example shown on how to access it using Python:
import urllib2
address="1600+Amphitheatre+Parkway,+Mountain+View,+CA"
url="https://maps.googleapis.com/maps/api/geocode/json?address=%s" % address
response = urllib2.urlopen(url)
jsongeocode = response.read()
I converted it to python 3.4, but the data that I'm obtaining is not in a valid JSON format. An alternative route is to use BeautifulSoup, but I'm not trying to do anything complicated.
This is the code that I'm using with Python 3.4:
import urllib.request
import json
address="1600+Amphitheatre+Parkway,+Mountain+View,+CA"
url="https://maps.googleapis.com/maps/api/geocode/json?address=%s" % address
with urllib.request.urlopen(url) as link:
s = str(link.read())
print(json.dumps(s))
This is a snapshot of the data I'm receiving:
"b'{\n \"results\" : [\n {\n \"address_components\" : [\n {\n \"long_name\" : \"1600\",\n
\"short_name\" : \"1600\",
The problem you are having is that you are taking binary data and turning it into a string by wrapping it with str
. The proper way to turn binary data into a string in Python3 is to decode
it.
Thus, you should instead decode
your results into a string before attempting to interpret them as json (Python3.4 example):
with urllib.request.urlopen(url) as link:
s = link.read()
result = json.loads(s.decode('utf-8'))
But I also recommend giving requests a shot because it can simplify these steps for you:
>>> import requests
>>> resp = requests.get(url)
>>> resp.json()
{'status': 'OK', 'results': [{'types': ['street_address'], 'place_id': 'ChIJ2eUgeAK6j4ARbn5u_wAGqWA', 'address_components': [{'types': ['street_number'], 'long_name': '1600', 'short_name': '1600'}, {'types': ['route'], 'long_name': 'Amphitheatre Parkway', 'short_name': 'Amphitheatre Pkwy'}, {'types': ['locality', 'political'], 'long_name': 'Mountain View', 'short_name': 'Mountain View'}, {'types': ['administrative_area_level_2', 'political'], 'long_name': 'Santa Clara County', 'short_name': 'Santa Clara County'}, {'types': ['administrative_area_level_1', 'political'], 'long_name': 'California', 'short_name': 'CA'}, {'types': ['country', 'political'], 'long_name': 'United States', 'short_name': 'US'}, {'types': ['postal_code'], 'long_name': '94043', 'short_name': '94043'}], 'formatted_address': '1600 Amphitheatre Parkway, Mountain View, CA 94043, USA', 'geometry': {'location_type': 'ROOFTOP', 'viewport': {'northeast': {'lat': 37.4236854802915, 'lng': -122.0828811197085}, 'southwest': {'lat': 37.4209875197085, 'lng': -122.0855790802915}}, 'location': {'lat': 37.4223365, 'lng': -122.0842301}}}]}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments