pandas 将纬度和经度放入距离矩阵中,python中的谷歌地图API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36500331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Putting latitudes and longitudes into a distance matrix, google map API in python
提问by Johnnie
I have a pandas dataframe in the following format:dataframe.
我有一个以下格式的Pandas数据框:数据框。
Now I want to put all the pairs of Start Latitude and Start Longitude into origins and the put all the pairs of End Latitude and End Longitude into destinations.I want to get the distance and duration by each row like following. Expected Output:
现在我想把所有的开始纬度和开始经度对放到原点,把所有的结束纬度和结束经度对放到目的地。我想得到每一行的距离和持续时间,如下所示。预期输出:
Rental Id | Distance | Duration | Status
0 51649420 0 0 OK
1 51649421 959 214 OK
2
...
15
I tried following tow methods but both of them gave me timeout errors.
我尝试了以下两种方法,但它们都给了我超时错误。
Method 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']
Method 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))
Is there anyway to solve this problem? Thanks in advance.
有没有办法解决这个问题?提前致谢。
回答by AlexM
I'm surprised that you're getting a timeout error with Method 1. Can you confirm the output?
我很惊讶您在使用方法 1 时遇到超时错误。您能确认输出吗?
Have you created a Google Maps API key? It's free for standard use (2,500 distance calculations per day, limit 100 per query and limit 100 per 10 sec) https://developers.google.com/maps/documentation/distance-matrix/get-api-keyThat key needs to be written where your code has 'my API key'
您是否创建了 Google Maps API 密钥?标准使用免费(每天 2,500 次距离计算,每次查询限制 100 次,每 10 秒限制 100 次) https://developers.google.com/maps/documentation/distance-matrix/get-api-key该密钥需要写在你的代码有“我的 API 密钥”的地方
There may also be an issue with your indentation on the for loop, and assignment to orgins and destinations. Try this out:
您在 for 循环上的缩进以及对起点和目的地的分配也可能存在问题。试试这个:
# 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
回答by vikaschablani
16 * 16 = 256 > 100, so probably try with smaller matrix viz 10 X 10 and then it should work.
16 * 16 = 256 > 100,所以可能尝试使用较小的矩阵,即 10 X 10,然后它应该可以工作。