2016-04-08 6 views
4

Ich habe eine Pandas Datenrahmen in folgendem Format: dataframe. enter image description herePutting 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.

Antwort

0

Ich bin überrascht, dass Sie einen Timeout-Fehler mit Methode 1 erhalten. Können Sie die Ausgabe bestätigen?

Haben Sie einen Google Maps-API-Schlüssel erstellt? Es ist kostenlos für Standardanwendungen (2.500 Abstandsberechnungen pro Tag, 100 pro Abfrage begrenzen und 100 pro 10 sec) limit https://developers.google.com/maps/documentation/distance-matrix/get-api-key Das Schlüssel muss geschrieben werden, in dem den Code hat ‚meinen API-Schlüssel‘

Es kann auch sein, ein Problem mit Ihrem Einzug in der for-Schleife und Zuordnung zu orgins und Destinationen. Probieren Sie dies aus:

# make sure you can connect to Google's server 
import requests 
try: 
    response = requests.get('http://www.google.com') 
except: 
    print 'Can\'t connect to Google\'s server' 
    raw_input('Press any key to exit.') 
    quit() 

# use the Google Maps API 
import googlemaps 
gmaps = googlemaps.Client(key='YOUR KEY') 
origins = [] 
destinations = [] 
for i in range (0,15): 
    origins.append(str(journeydf['Start Latitude'][i]) + ' ' + str(journeydf['Start Longitude'][i])) 
    destinations.append(str(journeydf['End Latitude'][i]) + ' ' + str(journeydf['End Longitude'][i])) 
matrix = gmaps.distance_matrix(origins, destinations, mode="bicycling") 
print matrix 
+0

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

0

16 * 16 = 256> 100, also wahrscheinlich versuchen, mit kleineren Matrix nämlich 10 X 10 und dann sollte es funktionieren.

+0

Ich hatte auch Timeouts und das hat mir wirklich geholfen. Ich hatte 144 Kombinationen, reduziert auf 96 und es hat funktioniert. – nitzpo

Verwandte Themen