0

I need assistance handling the dict file type that is returned from the google maps api.

Currently, the results are handing me a dict of the resulting data (starting addresses, ending addresses, travel times, distances etc) which I cannot process. I can extract the start and end addresses simply, but the bulk data is proving difficult to extract, and I think it is because of its structure.

The sample of the code I have is as follows;

import googlemaps
import csv
import pandas as pd
postcodes = pd.read_csv("SW.csv", sep=',', usecols=['postcode'], squeeze=True)
infile1 = open('SW.csv', 'r')
reader1 = csv.reader(infile1)
Location1 = postcodes[0:10]
Location2 = 'SW1A 2HQ'
my_distance = gmaps.distance_matrix(Location1, Location2, mode='bicycling', language=None, avoid=None, units='metric',
                                        departure_time='2475925955', arrival_time=None,
                                        transit_routing_preference=None)
print(my_distance)

Which generates the following output;

{'origin_addresses': ['Cossar Mews, Brixton, London SW2 2TR, UK', 'Bushnell Rd, London SW17 8QP, UK', 'Maltings Pl, Fulham, London SW6 2BX, UK', 'Knightsbridge, London SW7 1BJ, UK', 'Chelsea, London SW3 3EE, UK', 'Hester Rd, London SW11 4AJ, UK', 'Brixton, London SW2 1HZ, UK', 'Randall Cl, London SW11 3TG, UK', 'Sloane St, London SW1X 9SF, UK', 'Binfield Rd, London SW4 6TA, UK'], 'rows': [{'elements': [{'duration': {'text': '28 mins', 'value': 1657}, 'status': 'OK', 'distance': {'text': '7.5 km', 'value': 7507}}]}, {'elements': [{'duration': {'text': '31 mins', 'value': 1850}, 'status': 'OK', 'distance': {'text': '9.2 km', 'value': 9176}}]}, {'elements': [{'duration': {'text': '27 mins', 'value': 1620}, 'status': 'OK', 'distance': {'text': '7.0 km', 'value': 7038}}]}, {'elements': [{'duration': {'text': '16 mins', 'value': 953}, 'status': 'OK', 'distance': {'text': '4.0 km', 'value': 4038}}]}, {'elements': [{'duration': {'text': '15 mins', 'value': 899}, 'status': 'OK', 'distance': {'text': '3.4 km', 'value': 3366}}]}, {'elements': [{'duration': {'text': '21 mins', 'value': 1260}, 'status': 'OK', 'distance': {'text': '5.3 km', 'value': 5265}}]}, {'elements': [{'duration': {'text': '28 mins', 'value': 1682}, 'status': 'OK', 'distance': {'text': '7.5 km', 'value': 7502}}]}, {'elements': [{'duration': {'text': '23 mins', 'value': 1368}, 'status': 'OK', 'distance': {'text': '5.9 km', 'value': 5876}}]}, {'elements': [{'duration': {'text': '14 mins', 'value': 839}, 'status': 'OK', 'distance': {'text': '3.3 km', 'value': 3341}}]}, {'elements': [{'duration': {'text': '16 mins', 'value': 982}, 'status': 'OK', 'distance': {'text': '4.3 km', 'value': 4294}}]}], 'destination_addresses': ['Horse Guards Rd, London SW1A 2HQ, UK'], 'status': 'OK'}

I am then using the following code to extract it;

origin = my_distance['origin_addresses']
dest = my_distance['destination_addresses']
dist = my_distance['rows']

I have tried the df_from_list and many others to try and process the dist data. The end goal is to have a matrix with the origin addresses on each row, the destination addresses forming columns, with distance and time as data variables within these columns.

Something similar to this

        |         DEST 1        |        DEST 2         |
        |   TIME    |      DIST |      TIME |      DIST |
START 1 |      X    |      Y    |     Z     |       T   |
START 2 |      A    |      B    |     C     |       T   |

Please can someone help me process the my_distance output (shown above) into an architecture similar to that shown above.

Thanks!

2 Answers 2

2

This basicly creates a dictionary with the starts and the destination adresses. The destination adresses have a list of tupels as values. The first element in the tuple is the duration and the second the distance e.g. (45, 7.0)#45=45min and 7.0 = 7km. Then I create the dataframe with pandas.DataFrame.from_dict()

import pandas as pd

dct = {d_adresses:[] for d_adresses in data['destination_addresses']}
dct['starts'] = []
for i in range(len(data['origin_addresses'])):
    duration=int(data['rows'][i]['elements'][0]['duration']['text'].split(' ')[0])
    distance=float(data['rows'][i]['elements'][0]['distance']['text'].split(' ')[0])

    for key in dct:
        if key != 'starts':
            dct[key].append((duration, distance))

    dct['starts'].append(data['origin_addresses'][i])
df = pd.DataFrame.from_dict(dct)
df.set_index('starts', inplace=True)
1
  • This created duplicate column values for each destination. I had to extract the duration and distance using origin (i) and destination (key) inside the second for loop Dec 28, 2021 at 18:08
1

I create an empty dataframe before running gmaps.distance_matrix, and place the dictionary keys into the dataframe. Similar to the above solution:

    traffic = pd.DataFrame({'time': [], 'origins': [], 'destinations': [], 'destination_addresses': [], 'origin_addresses': [], 'rows': [], 'status': []})

    for origin in origins:
        for destination in destinations:
            traffic = traffic.append({'time': [00:00], 'origins': [origin], 'destinations': [destination]}, ignore_index=True)

            if origin != destination:
                if cityname == cityname:

                    # Get travel distance and time for a matrix of origins and destinations
                    traffic_result = gmaps.distance_matrix((origin), (destination),
                                        mode="driving", language=None, avoid=None, units="metric",
                                        departure_time=00:00, arrival_time=None, transit_mode=None,
                                        transit_routing_preference=None, traffic_model=None, region=None)

                    for key in traffic_result.keys():
                        for value in traffic_result[key]:
                            print(key, value)
                            traffic = traffic.append({key: [value]}, ignore_index=True)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.