2012-08-08 26 views
2

我想允許用戶使用我的應用程序向Google地圖添加地點。本教程演示如何實現地方搜索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正文。我想利用這個代碼,但適應它放在地址:實現基本Google地方使用Python添加

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 

回答

0

如果您閱讀http://docs.python.org/library/urllib2的urllib2文檔,它清楚地指出以下內容:

「urllib2.urlopen(URL [,數據] [,超時])

數據可以是指定的附加數據如果不需要這樣的數據,以發送到服務器, 或無字符串。目前HTTP請求只有使用數據的請求是 ;當提供數據參數時,HTTP請求將成爲POST而不是 GET。數據應該是標準應用程序/ x-www-form-urlencoded格式的 中的緩衝區。該 urllib.urlencode()函數的2元組 的映射或序列,並在此格式」

所以返回一個字符串,你需要調用的數據參數的urlopen函數,然後將發送請求通過POST。此外,通過Google Places Add API頁面查看,您需要準備包含位置,成本等urlencode()的數據,並且您應該很好。 https://gist.github.com/1841962#file_http_post_httplib.py