我尝试使用google maps api(地理编码API)密钥连接我的代码。 但是当我运行我的代码时,会发生ValueError。我不知道为什么。 这可能很傻,但请帮助我。
这是我的python代码。
import httplib2
import json
def getGeocodeLocation(inputString):
google_api_key = "MY_API_KEY"
locationString = inputString.replace(" ", "+")
url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s & key=%s' % (locationString, google_api_key))
h = httplib2.Http()
response, content = h.request(url, 'GET')
result = json.loads(content)
print "response header: %s \n \n" % response
return result
这就是错误。
>>> from geocode import getGeocodeLocation
>>> getGeocodeLocation("Dalls, Texas")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "geocode.py", line 10, in getGeocodeLocation
result = json.loads(content)
File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
感谢。
+
当我编辑代码时,
response, content = h.request(url, 'GET')
result = json.loads(content)
print "response header: %s \n \n" % response
到
response, content = h.request(url, 'GET')
print "response header: %s \n \n" % response
result = json.loads(content)
结果是这样的。
{u'status': u'OK',
u'results':
[
{u'geometry':
{u'location_type': u'APPROXIMATE',
u'bounds':
{u'northeast': {u'lat': 33.0237921, u'lng': -96.4637379},
u'southwest': {u'lat': 32.617537, u'lng': -96.999347}},
u'viewport':
{u'northeast': {u'lat': 33.0237921, u'lng': -96.4637379},
u'southwest': {u'lat': 32.617537, u'lng': -96.999347}},
u'location': {u'lat': 32.7766642, u'lng': -96.79698789999999}
},
u'address_components':
[
{u'long_name': u'Dallas',
u'types': [u'locality', u'political'],
u'short_name': u'Dallas'},
{u'long_name': u'Dallas County',
u'types': [u'administrative_area_level_2', u'political'],
u'short_name': u'Dallas County'},
{u'long_name': u'Texas',
u'types': [u'administrative_area_level_1', u'political'],
u'short_name': u'TX'},
{u'long_name': u'United States',
u'types': [u'country', u'political'],
u'short_name': u'US'}
],
u'place_id': u'ChIJS5dFe_cZTIYRj2dH9qSb7Lk',
u'formatted_address': u'Dallas, TX, USA',
u'types': [u'locality', u'political']
}
]
}
答案 0 :(得分:1)
您的请求中有错误。状态代码为400 Bad Request,您的回复内容为:
您的客户发出了格式错误或非法的请求。这就是我们所知道的。
这一行似乎有错误:
url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s & key=%s' % (locationString, google_api_key))
&amp; 标志周围不应有空格:
url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s' % (locationString, google_api_key))