2013-07-25 26 views
1
import urllib,urllib2 
try: 
    import json 
except ImportError: 
    import simplejson as json 
params = {'q': '207 N. Defiance St, Archbold, OH','output': 'json', 'oe': 'utf8'} 
url = 'http://maps.google.com/maps/geo?' + urllib.urlencode(params) 

rawreply = urllib2.urlopen(url).read() 
reply = json.loads(rawreply) 
print (reply['Placemark'][0]['Point']['coordinates'][:-1]) 

在執行此代碼即時得到一個錯誤創建谷歌的地圖API客戶端:獲得KeyError異常,同時使用的urllib,urllib2的和JSON模塊

回溯(最近通話最後一個): 文件「C:/ Python27/Foundations_of_networking/search2.py「,第11行,在 print(reply ['Placemark'] [0] ['Point'] ['coordinates'] [: - 1]) KeyError:'Placemark'

如果有人知道解決方法,請幫助我。我只是python的新手。

回答

3

如果只打印reply你會看到這一點:

{u'Status': {u'code': 610, u'request': u'geocode'}} 

您正在使用API​​的棄用版本。轉到v3。看看this page頂部的通知。

我還沒有這個API之前使用,但下面放倒我送行(從here拍攝):

New endpoint

The v3 Geocoder uses a different URL endpoint:

http://maps.googleapis.com/maps/api/geocode/output?parameters Where output can be specified as json or xml.

Developers switching from v2 may be using a legacy hostname — either maps.google.com, or maps-api-ssl.google.com if using SSL. You should migrate to the new hostname: maps.googleapis.com. This hostname can be used both over both HTTPS and HTTP.

嘗試以下操作:

import urllib,urllib2 
try: 
    import json 
except ImportError: 
    import simplejson as json 
params = {'address': '207 N. Defiance St, Archbold, OH', 'sensor' : 'false', 'oe': 'utf8'} 
url = 'http://maps.googleapis.com/maps/api/geocode/json?' + urllib.urlencode(params) 

rawreply = urllib2.urlopen(url).read() 
reply = json.loads(rawreply) 

if reply['status'] == 'OK': 
    #supports multiple results 
    for item in reply['results']: 
     print (item['geometry']['location']) 

    #always chooses first result 
    print (reply['results'][0]['geometry']['location']) 
else: 
    print (reply) 

上面我已經展示了兩種方法訪問結果的經度和緯度。 for循環將支持返回多個結果的情況。第二個簡單地選擇第一個結果。請注意,無論哪種情況,我都會首先檢查退貨的status以確保實際數據恢復。

如果您要訪問的緯度和經度獨立,你可以這樣做是這樣的:

# in the for loop 
lat = item['geometry']['location']['lat'] 
lng = item['geometry']['location']['lng'] 

# in the second approach 
lat = reply['results'][0]['geometry']['location']['lat'] 
lng = reply['results'][0]['geometry']['location']['lng'] 
+0

@布賴恩..以上代碼正在工作..但如果我只想看到經度和緯度..然後什麼樣的變化我不得不在上面的代碼。 – Jaassi

+0

@ user2433888我已更新答案以顯示訪問座標 – Brian

0

剛打印出來的原始的回覆,看什麼鍵它,然後訪問鍵,如果你這樣做:

print (reply["Status"]), 

你會得到:

{u'code': 610, u'request': u'geocode'} 

和你的整個JSON的樣子這樣的:

{u'Status': {u'code': 610, u'request': u'geocode'}} 

所以如果你要訪問的代碼只是做:

print(reply["Status"]["code"]) 
+0

@Pawelmhm ...如果我只是想看看緯度和經度..那麼在上面的代碼中我必須做什麼改變。 – Jaassi

0

當您試圖訪問對象上不存在的鍵時,會引發KeyError異常。

我打印響應文本中rawreply:

>>> print rawreply 
... { 
     "Status": { 
     "code": 610, 
     "request": "geocode" 
     } 
    } 

所以問題是,你沒有收到預期的響應,有它在沒有「標」鍵,等於是例外。

請在Google Maps API上查找代碼610的含義,也許您沒有做出正確的查詢,或者您在訪問之前必須先檢查響應。