谷歌地圖API我有以下格式的熊貓數據幀:dataframe. 把緯度和經度到距離矩陣,在蟒蛇
現在我希望把所有對啓動緯度和啓動經度爲起源並把所有的「結束緯度」和「結束經度」對放入目的地。我想要按照以下方式獲得每行的距離和持續時間。預期輸出:
Rental Id | Distance | Duration | Status
0 51649420 0 0 OK
1 51649421 959 214 OK
2
...
15
我試過下面兩種方法,但他們都給我超時錯誤。
方法1:
import googlemaps
from pandas.io.json import json_normalize
gmaps = googlemaps.Client(key='my API key')
for i in range (0,15):
origins = (journeydf['Start Latitude'][i], journeydf['Start Longitude'][i])
destinations = (journeydf['End Latitude'][i], journeydf['End Longitude'][i])
matrix = gmaps.distance_matrix(origins, destinations, mode="bicycling")
matrixdf = json_normalize(matrix,['rows','elements'])
matrixdf['Rental Id']=journeydf['Rental Id']
方法2:
import urllib, json, time
import pandas as pd
def google(lato, lono, latd, lond):
url = """http://maps.googleapis.com/maps/api/distancematrix/json?origins=%s,%s"""%(lato, lono)+ \
"""&destinations=%s,%s&mode=driving&language=en-EN&sensor=false"""% (latd, lond)
#CHANGE THIS FOR PYTHON 3.X TO urllib.request.urlopen(url)...
response = urllib.urlopen(url).read().decode('utf8')
#Wait a second so you don't overwhelm the API if doing lots of calls
time.sleep(1)
obj = json.loads(response)
try:
minutes = obj['rows'][0]['elements'][0]['duration']['value']/60
miles = (obj['rows'][0]['elements'][0]['distance']['value']/100)*.62137 #kilometers per mile
return minutes, miles
except IndexError:
#something went wrong, the result was not found
print (url)
#return the error code
return obj['Status'], obj['Status']
def ApplyGoogle(row):
lato, lono = row['Start Latitude'], row['Start Longitude']
latd, lond = row['End Latitude'], row['End Longitude']
return google(lato, lono, latd, lond)
journeydf['Minutes'], journeydf['Miles'] = zip(*journeydf.apply(ApplyGoogle, axis = 1))
反正是有解決這個問題?提前致謝。
仍然我收到超時錯誤。我已經創建了Google地圖API並將其放入'我的API密鑰'中。當我是1時,它肯定適用於特定情況。我認爲循環中存在問題。 – Johnnie