Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 views
in Technique[技术] by (71.8m points)

json - Using Google Maps geocoder from Python with urllib2

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...