Google距离矩阵不包含村庄

时间:2019-06-25 22:21:40

标签: python google-maps google-maps-api-3 directions google-distancematrix-api

我编写了一个函数,该函数获取包含城市/村庄名称的输入。现在看来,Google API方向矩阵无法识别给定的值之一。有人知道如何获得结果吗?如果我在Google Maps中输入村庄名称(荷兰的Erp),它会毫不费力地找到它。

函数代码:

def calc_dist(dest):
    jsonReq = json.load(uReq(jsonURL + source + "&destinations=" + dest + 
    "&key=" + googleAPI))
    distance = jsonReq['rows'][0]['elements'][0]['distance']['value']
    return distance

错误是:

Traceback (most recent call last):
File "webscraper_tester.py", line 88, in <module>
distance = str(calc_dist(destination))
File "webscraper_tester.py", line 25, in calc_dist
distance = jsonReq['rows'][0]['elements'][0]['distance']['value']
KeyError: 'distance'

生成的URL如下:

https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=Nijmegen,GE&destinations=Erp,NB&key="API-KEY"

1 个答案:

答案 0 :(得分:1)

Google Maps在其各种API中使用ISO 3166-1国家/地区代码,并且在查找位置时最好包含国家/地区代码。

荷兰的国家/地区代码为NL。如果我重写了您的请求,请删除看起来像是您所包含的区域代码,然后添加国家/地区代码,如下所示:

https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=Nijmegen,NL&destinations=Erp,NL&key=YOUR_KEY

然后返回:

{
  "destination_addresses": [
    "5469 Erp, Netherlands"
  ],
  "origin_addresses": [
    "Nijmegen, Netherlands"
  ],
  "rows": [{
    "elements": [{
      "distance": {
        "text": "45.7 km",
        "value": 45652
      },
      "duration": {
        "text": "35 mins",
        "value": 2113
      },
      "status": "OK"
    }]
  }],
  "status": "OK"
}