Ich habe eine Pandas Datenrahmen in folgendem Format: dataframe. Putting Breiten und Längen in einer Distanzmatrix, google map API in Python
Jetzt möchte ich alle Paare von Anfang Latitude und Start Länge in Ursprünge setzen und die alle Paare von End Latitude und End Longitude in Destinationen setzen. Ich möchte die Entfernung und Dauer für jede Zeile wie folgt erhalten. Erwartete Ausgabe:
Rental Id | Distance | Duration | Status
0 51649420 0 0 OK
1 51649421 959 214 OK
2
...
15
Ich habe versucht, Schleppmethoden, aber beide gaben mir Timeout-Fehler.
Methode 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']
Methode 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))
Gibt es trotzdem, um dieses Problem zu lösen? Danke im Voraus.
Immer noch bekomme ich einen Timeout-Fehler. Ich habe bereits Google Maps API erstellt und das in "meinen API-Schlüssel" eingefügt. Es funktioniert definitiv für den speziellen Fall, wenn ich 1 bin. Ich denke, es gibt ein Problem in der Schleife. – Johnnie