将经纬度放入距离矩阵中,使用Python中的Google Map API

7
我有一个pandas数据帧,格式如下:dataframe. enter image description here 现在我想把所有的起始纬度和起始经度对放入origins中,并将所有的结束纬度和结束经度对放入destinations中。我想要按行获取距离和持续时间,如下所示。期望输出:
    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']

方法二:

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))

有没有什么办法可以解决这个问题?先谢谢了。
2个回答

1
我很惊讶你使用方法1时出现了超时错误。你能确认输出吗?
你创建了谷歌地图API密钥吗?标准用途是免费的(每天2500次距离计算,限制100次查询和每10秒钟限制100次)。https://developers.google.com/maps/documentation/distance-matrix/get-api-key。该密钥需要写在代码中的“我的API密钥”处。
还可能存在for循环缩进和orgins和destinations分配的问题。请尝试以下内容:
# 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 Maps API 并将其放入“我的 API 密钥”中。在 i 等于 1 的特定情况下它绝对是有效的。我认为循环中存在问题。 - Johnnie

0

16 * 16 = 256 > 100,因此建议尝试使用较小的矩阵,例如10 X 10,然后应该可以正常工作。


我也遇到了超时问题,这个方法确实帮了我。我有144种组合,缩减到96种后就可以正常工作了。 - nitzpo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接