2

我想允许用户使用我的应用向 Google 地图添加地点。本教程展示了如何实现地点搜索https://developers.google.com/academy/apis/maps/places/basic-place-search我理解代码,但地点搜索和地点添加是不同的。在 Place Add 中,我们必须使用 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
4

1 回答 1

0

如果您阅读http://docs.python.org/library/urllib2上的 urllib2 文档,它清楚地说明了以下内容:

“urllib2.urlopen(url [,数据] [,超时])

data 可以是一个字符串,指定要发送到服务器的附加数据,或者如果不需要此类数据,则为 None。目前 HTTP 请求是唯一使用数据的请求;当提供数据参数时,HTTP 请求将是 POST 而不是 GET。data 应该是标准 application/x-www-form-urlencoded 格式的缓冲区。urllib.urlencode() 函数采用 2 元组的映射或序列,并以这种格式返回一个字符串”

So, you need to call the urlopen function with data parameter which will then send the request through POST. Also. looking through the Google Places Add API page, you need to prepare the data which includes location, accruracy etc. urlencode() it and you should be good. If you want an example, see this gist at: https://gist.github.com/1841962#file_http_post_httplib.py

于 2012-08-08T01:21:21.870 回答