Using google maps geocoding with python using urllib2
I'm trying to use the Google Maps geocoder with Python and JSON, but I'm told that I have a bad request:
add = "Buckingham Palace, London, SW1A 1AA"
geocode_url = "https://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false®ion=uk" % add
print geocode_url
req = urllib2.urlopen(geocode_url)
jsonResponse = json.loads(f.read())
pprint.pprint(nest)
It doesn't work with urllib2.HTTPError: HTTP Error 400: Bad Request
.
But if I just copy and paste
https://maps.googleapis.com/maps/api/geocode/json?address=Buckingham%20Palace,%20London,%20SW1A%201AA&sensor=false®ion=uk
into the browser bar, it works fine.
What's wrong with my request?
+3
source to share
1 answer
You need some url encoding, this works:
import urllib2
import pprint
import json
add = "Buckingham Palace, London, SW1A 1AA"
add = urllib2.quote(add)
geocode_url = "http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false®ion=uk" % add
print geocode_url
req = urllib2.urlopen(geocode_url)
jsonResponse = json.loads(req.read())
pprint.pprint(jsonResponse)
The add = urllib2.quote (add) line is an important point. If you have non-latin characters, you should be aware that the google API requires UTF-8 encoding.
+6
source to share