将纬度和经度放入距离矩阵,python中的google map API
Posted
技术标签:
【中文标题】将纬度和经度放入距离矩阵,python中的google map API【英文标题】:Putting latitudes and longitudes into a distance matrix, google map API in python 【发布时间】:2016-07-29 18:14:56 【问题描述】:我有一个以下格式的熊猫数据框:dataframe.
现在我想将所有开始纬度和开始经度对放入起点,并将所有结束纬度和结束经度对放入目的地。我想通过每一行获得距离和持续时间,如下所示。预期输出:
Rental Id | Distance | Duration | Status
0 51649420 0 0 OK
1 51649421 959 214 OK
2
...
15
我尝试了以下两种方法,但它们都给了我超时错误。
方法一:
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']
方法二:
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))
有没有办法解决这个问题?提前致谢。
【问题讨论】:
【参考方案1】:我很惊讶您在使用方法 1 时遇到超时错误。您能确认输出吗?
您是否创建了 Google Maps API 密钥?标准使用免费(每天 2,500 次距离计算,每次查询限制 100 次,每 10 秒限制 100 次) https://developers.google.com/maps/documentation/distance-matrix/get-api-key 该密钥需要写在您的代码具有“我的 API 密钥”的地方
您在 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
【讨论】:
我仍然收到超时错误。我已经创建了 Google 地图 API 并将其放入“我的 API 密钥”中。当 i 为 1 时,它肯定适用于特定情况。我认为循环中存在问题。【参考方案2】:16 * 16 = 256 > 100,所以可能尝试使用较小的矩阵,即 10 X 10,然后它应该可以工作。
【讨论】:
我也有超时,这实际上帮助了我。我有 144 种组合,减少到 96 种,它奏效了。以上是关于将纬度和经度放入距离矩阵,python中的google map API的主要内容,如果未能解决你的问题,请参考以下文章