Jaeho Jung
Jaeho Jung

Reputation: 103

Import google maps distance matrix result into an excel file

I am trying to get distances and durations between two places. I have about 2000 combinations (actually, 10000 combinations in excel file. I have to split them into 5 excel files because of daily limitation by google) and I tried to use a python for this task.

I succeeded to get the results but it is too messy and difficult to save in excel file with name as "result".

Could anyone suggest me a way to save the result in an excel file?

Here is my code and I attached a result file that I could obtain.

#way1

import googlemaps

gmaps = googlemaps.Client('--')#directions

import os
import csv

def get_file_path(filename):

    currentdirpath=os.getcwd()

    file_path = os.path.join(os.getcwd(), filename)

    print (file_path)

    return file_path

path = "C:\\----\\com(eng)1-1.csv"

def read_csv(filepath):

    with open(filepath, 'rU', encoding="utf8") as csvfile:

        reader = csv.reader(csvfile)

        for row in reader:

            my_distance = gmaps.distance_matrix(row[0]+", seoul", row[2], mode="transit")
            print (my_distance)

read_csv(path)

Here is what I could obtain from the code;

enter image description here

From the results, I need a distance and duration only in the excel file but I don't know how to import them into the excel file. Could anyone help me to do this?

Upvotes: 0

Views: 925

Answers (1)

yslee
yslee

Reputation: 236

So the image shows the result from 'print(my_distance)' right?
You can easily handle the result using json module like this.

import json

def read_csv(filepath):

    with open(filepath, 'rU', encoding="utf8") as csvfile:
        reader = csv.reader(csvfile)

        for row in reader:
            my_distance = gmaps.distance_matrix(row[0]+", seoul", row[2], mode="transit")
            print (my_distance)
            
            result_dict = json.loads(my_distance)
            distance = result_dict['distance']['value'] # meters
            duration = result_dict['duration']['value'] # seconds

            # do something 

read_csv(path)

More information about json: https://en.wikipedia.org/wiki/JSON

Upvotes: 1

Related Questions