python - 使用 Python 实现基本的 Google Place Add

标签 python google-maps-api-3 urllib2

我想允许用户使用我的应用向 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/

相关文章:

c++ - 在 Python (linux) 中调用复杂的 C++ 函数

命令提示符中未显示 Python 版本

javascript - 从字段进行搜索后如何将可拖动标记添加到谷歌地图

javascript - 带有 Google Map API 的基本 KML 不起作用

javascript - 将地址字段转换为坐标

python - 通过 urllib2 将 SQL 数据库耦合到 Python 应用程序

python - Py2Exe openpyxl导入错误

python - 尝试在 Windows 上的 Python 3 中使用套接字时出现 Winsock 错误 10014

python - 如何从无空格字符串中提取数据?

python - 从企业防火墙后面使用 urllib2 打开网站 - 11004 getaddrinfo 失败