python googlemaps不同位置之间的所有可能距离

时间:2017-11-08 19:43:47

标签: python python-3.x google-maps

% productbuild --distribution Distribution.xml --sign "Developer ID Installer" --resources . InstallIntonia1.4.0.pkg

名单的要素是学校。我不想让列表很长,所以我使用了这些缩写。 我希望得到" GSGS"之间的所有距离。和列表中的学校。我不知道在第二个括号内写什么。

schools=['GSGS','GSGL','JKG','JMG','MCGD','MANGD','SLSA','WHGR','WOG','GCG','LP', 
  'PGG', 'WVSG', 'ASGE','CZG', 'EAG','GI'] 

for i in range (1,17):
    gmaps = googlemaps.Client(key='')
    distances = gmaps.distance_matrix((GSGS), (schools), mode="driving"['rows'][0]['elements'][0]['distance']['text']
    print(distances)

如果我这样运行它会输出此错误:

distances = gmaps.distance_matrix((GSGS), (schools)

我可以一对一地做,但这不是我想要的。如果我从列表学校写另一所学校并删除for循环,它可以正常工作。

我知道我必须做一个循环,以便它循环通过列表,但我不知道该怎么做。在每个变量的背后,例如" GSGS"是学校的地址/位置。 为了安全起见,我删除了密钥。

2 个答案:

答案 0 :(得分:0)

根据我的经验,当您使用第三方API时,有时很难知道发生了什么。虽然我不是重新发明轮子的支持者,但有时需要全面了解正在发生的事情。所以,我建议给它一个建立你自己的api端点请求调用的镜头,看看是否有效。

import requests

schools = ['GSGS','GSGL','JKG','JMG','MCGD','MANGD','SLSA','WHGR','WOG','GCG','LP','PGG', 'WVSG', 'ASGE','CZG', 'EAG','GI']

def gmap_dist(apikey, origins, destinations, **kwargs):
    units = kwargs.get("units", "imperial")
    mode = kwargs.get("mode", "driving")
    baseurl = "https://maps.googleapis.com/maps/api/distancematrix/json?"
    urlargs = {"key": apikey, "units": units, "origins": origins, "destinations": destinations, "mode": mode}
    req = requests.get(baseurl, params=urlargs)
    data = req.json()

    print(data)

    # do this for each key and index pair until you 
    # find the one causing the problem if it 
    # is not immediately evident from the whole data print
    print(data["rows"])
    print(rows[0])


    # Check if there are elements
    try:
       distances = data['rows'][0]['elements'][0]['distance']
    except KeyError:
        raise KeyError("No elements found")
    except IndexError:
        raise IndexError("API Request Error. No response returned")
    else:
        return distances  

另外作为一般的经验法则,最好有一个测试用例,以确保在测试整个列表之前事情正常进行,

#test case
try:
    test = gmap_dist(apikey="", units="imperial", origins="GSGS", destinations="GSGL", mode="driving")
except Exception as err:
    raise Exception(err)
else:
    dists = gmap_dist(apikey="", units="imperial", origins="GSGS", destinations=schools, mode="driving")
    print(dists)

最后,如果您正在测试距离" GSGS"到其他学校,那么你可能想把它从学校名单中删除,因为距离将是0。

现在,我怀疑你得到这个异常的原因是因为没有返回json元素。可能是因为您的某个参数格式不正确。

如果此函数仍然返回KeyError。检查地址拼写并确保您的apikey有效。虽然如果它是Apikey我会期望他们不会费心给你甚至空洞的结果。

希望这会有所帮助。评论它是否起作用。

答案 1 :(得分:0)

我父亲帮助了我,我们解决了这个问题。现在我有我想要的东西:)现在我必须列出学校之间的所有距离。如果我得到了,我必须使用Dijkstra算法来找到它们之间的最短路径。谢谢你的帮助!

import googlemaps

GSGS = (address)
GSGL = (address)
.    .     .
.    .     .
.    .     .

schools = 
(GSGS,GSGL,JKG,JMG,MCGD,MANGD,SLSA,WHGR,WOG,GCG,LP,PGG,WVSG,ASGE,CZG,EAG,GI)

school_names = ("GSGS","GSGL","JKG","JMG","MCGD","MANGD","SLSA","WHGR","WOG","GCG","LP","PGG","WVSG","ASGE","CZG","EAG","GI")

school_distances = ()
for g in range(0,len(schools)):
n = 0
    for i in schools:
        gmaps = googlemaps.Client(key='TOPSECRET')
        distances = gmaps.distance_matrix(schools[g], i)['rows'][0]['elements'][0]['distance']['text']
    if school_names[g] != school_names[n]:
        print(school_names[g] + " - " + school_names[n] + " " + distances)
    else:
        print(school_names[g] + " - " + school_names[n] + " " + "0 km")
    n = n + 1