简体   繁体   中英

googlemaps returning list instead of dict

I'm relative new to Python, so I hope this question is not too stupid. I have several coordinates (latitudes and longitudes) and I want to compute the driving distance and time using the Google Maps API. I'm following the code in http://py-googlemaps.sourceforge.net/

For now, I'm trying only one pair of origin-destination. Here is my code:

    import os
    import csv
    from googlemaps import Client

    ## Working directory
    wdir = 'mydir'
    os.chdir(wdir)

    ## Import data
    rowsarray=[]

    with open(os.path.relpath("Data/geocodes.csv"), "rb") as csvfile:
         reader = csv.reader(csvfile, delimiter=",")
         for row in reader:
            rowsarray.append(row)

    ## Google Maps
    gmaps = Client('mykey')        

    origin = float(rowsarray[1][0]),float(rowsarray[1][1])
    destination = float(rowsarray[1][2]),float(rowsarray[1][3])

    dirs = gmaps.directions(origin, destination)
    time = dirs['Directions']['Duration']['seconds']
    distance = dirs['Directions']['Distance']['meters']

My problem is that I cannot recover the time and distance. The error I get is:

    Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
    TypeError: list indices must be integers, not str  

I don't know why, but the object 'dirs' is a list and not a dict. I believe there is something really simple that I'm missing, but I can't figure out what it is. Just for the reference, I believe origin and destination are in the correct format, for example:

    origin
    (-23.9592578, -46.3744664)
    destination
    (-23.6605557, -47.2263173)

I appreciate any help!

This API is rather old, you might prefer to use the REST API like this:

import json
import urllib

origin = (-30.2664935,-51.8364501)
destination = (-30, -51)

geocode_url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng={[lat]},{[lon]}&sensor=false'
directions_url = 'http://maps.googleapis.com/maps/api/directions/json?sensor=false&origin={}&destination={}'

distance = 0;
duration = 0;

pars = (origin, destination)
request_url = directions_url.format(*pars)
result_string = urllib.urlopen(request_url).read();
result = json.loads(result_string)
if result['status'] == "OK":
    routes = result['routes']
    for route in routes:
        legs = route['legs']
        for leg in legs:
            distance += leg['distance']['value']
            duration += leg['duration']['value']

print distance, duration

如果您仍然想使用googlemaps python模块,请尝试以下操作:

print dirs[0]['Duration']['seconds']

Your object dirs is a list that contains one item, which is the dict you seek.

type(dirs) # returns type 'list'
type(mapresults[0]) # returns type 'dict'
tot_drive_time = dirs[0]['legs'][0]['duration']['value']
tot_distance = dirs[0]['legs'][0]['distance']['value']

FYI, the module googlemaps 2.4.2 was last updated 2015-12-03

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM