我是使用 Google 距离矩阵 API 的新手,我不断收到以下错误“KeyError:'距离'”,而不是距离值。类似问题的所有解决方案似乎都符合我正在使用的代码,其中列表“行”和“元素”中的第一项使用索引 [0] 访问,然后是“距离”和“值”项像字典一样访问。
这是相关的代码块:
# Loop through each row in the data frame using pairwise for (i1, row1), (i2, row2) in pairwise(df.iterrows()):
#Assign latitude and longitude as origin/departure points
LatOrigin = row1["latitude"]
LongOrigin = row1["longitude"]
origins = (LatOrigin,LongOrigin)
#Assign latitude and longitude from the next row as the destination point
LatDest = row2["latitude"] # Save value as lat
LongDest = row2["longitude"] # Save value as lat
destination = (LatDest,LongDest)
#pass origin and destination variables to distance_matrix function# output in meters
result = gmaps.distance_matrix(origins, destination, mode='walking')["rows"][0]["elements"][0]['distance']["value"]
#append result to list
list.append(result)
这是我期望的 JSON 有效负载的格式:
{
"originAddresses": [ "Greenwich, Greater London, UK", "13 Great Carleton Square, Edinburgh, City of Edinburgh EH16 4, UK" ],
"destinationAddresses": [ "Stockholm County, Sweden", "Dlouhá 609/2, 110 00 Praha-Staré Město, Česká republika" ],
"rows": [ {
"elements": [ {
"status": "OK",
"duration": {
"value": 70778,
"text": "19 hours 40 mins"
},
"distance": {
"value": 1887508,
"text": "1173 mi"
}
}, {
"status": "OK",
"duration": {
"value": 44476,
"text": "12 hours 21 mins"
},
"distance": {
"value": 1262780,
"text": "785 mi"
}
} ]
}, {
"elements": [ {
"status": "OK",
"duration": {
"value": 96000,
"text": "1 day 3 hours"
},
"distance": {
"value": 2566737,
"text": "1595 mi"
}
}, {
"status": "OK",
"duration": {
"value": 69698,
"text": "19 hours 22 mins"
},
"distance": {
"value": 1942009,
"text": "1207 mi"
}
} ]
} ]
}