我想允许用户使用我的应用向 Google map 添加地点。本教程介绍如何实现地点搜索 https://developers.google.com/academy/apis/maps/places/basic-place-search我理解代码,但地点搜索和地点添加是不同的。就地添加我们必须使用 POST URL 和 POST 正文 https://developers.google.com/places/documentation/?hl=fr#adding_a_place .我不知道如何在我的代码中插入 POST 正文。我想使用此代码,但要使其适应 Place Add:
import urllib2
import json
AUTH_KEY = 'Your API Key'
LOCATION = '37.787930,-122.4074990'
RADIUS = 5000
url = ('https://maps.googleapis.com/maps/api/place/search/json?location=%s'
'&radius=%s&sensor=false&key=%s') % (LOCATION, RADIUS, AUTH_KEY)
response = urllib2.urlopen(url)
json_raw = response.read()
json_data = json.loads(json_raw)
if json_data[‘status’] == ‘OK’:
for place in json_data['results']:
print ‘%s: %s\n’ % (place['name'], place['reference'])'
编辑
感谢@codegeek 的帮助我终于找到了基于这个库的解决方案https://github.com/slimkrazy/python-google-places
url = 'https://maps.googleapis.com/maps/api/place/add/json?sensor=false&key=%s' % AUTH_KEY
data = {
"location": {
"lat": 37.787930,
"lng": -122.4074990
},
"accuracy": 50,
"name": "Google Shoes!",
"types": ["shoe_store"]
}
request = urllib2.Request(url, data=json.dumps(data))
response = urllib2.urlopen(request)
add_response = json.load(response)
if add_response['status'] != 'OK':
# there is some error
最佳答案
如果您在 http://docs.python.org/library/urllib2 阅读了 urllib2 文档, 它清楚地说明了以下内容:
"urllib2.urlopen(url[, data][, timeout])
data may be a string specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format"
因此,您需要使用数据参数调用 urlopen 函数,然后通过 POST 发送请求。还。查看 Google Places Add API 页面,您需要准备包括位置、准确度等在内的数据。urlencode() 它应该很好。 如果您想要一个示例,请参阅以下要点: https://gist.github.com/1841962#file_http_post_httplib.py
关于python - 使用 Python 实现基本的 Google Place Add,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11856018/