3

I'm trying to use the Google Maps geocoder with Python and JSON, but keep being told 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&region=uk" % add
print geocode_url
req = urllib2.urlopen(geocode_url)
jsonResponse = json.loads(f.read())
pprint.pprint(nest) 

This fails with urllib2.HTTPError: HTTP Error 400: Bad Request.

But if I simply copy and paste

https://maps.googleapis.com/maps/api/geocode/json?address=Buckingham%20Palace,%20London,%20SW1A%201AA&sensor=false&region=uk

into a browser bar, it works fine.

What is wrong with my request?

1 Answer 1

6

You need some URL quoting 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&region=uk" % add
print geocode_url
req = urllib2.urlopen(geocode_url)
jsonResponse = json.loads(req.read())
pprint.pprint(jsonResponse) 

The line add = urllib2.quote(add) is the important point. If you have non latin characters be advised that the google API needs UTF-8 encoding.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.