I have a csv file that has 1800+ addresses. I need to compare the distance of every single one of them with a specific address. I wrote a code that does that But only if I add the address manually.
I want to run this code on every line of the csv file and print the distance in km and in minutes. How can I do that?
This is my code:
# Needed to read json and to use the endpoint request
import urllib.request
import json
# Google MapsDdirections API endpoint
endpoint = 'https://maps.googleapis.com/maps/api/directions/json?'
api_key = 'add api'
# Give the original work address and lists of addresses.
# Format has to be (Number Street Name City Province)
# So for example 1280 Main Strret Hamilton ON
origin = ('add the one address to calculate distance with the other').replace(' ', '+')
destinations = ['address1', 'address2', 'address3']
distances = []
# Goes through the array of addresses and calculated each of their distances
for i in range(len(destinations)):
    # Replaces the spaces with + so that it can properly work with the google maps api url
    currentDestination = destinations[i].replace(' ', '+')
    # Building the URL for the request
    nav_request = 'origin={}&destination={}&key={}'.format(origin, currentDestination, api_key)
    # Builds the request to be sent
    request = endpoint + nav_request
    # Sends the request and reads the response.
    response = urllib.request.urlopen(request).read()
    # Loads response as JSON
    directions = json.loads(response)
    # Gets the distance from the address in the array to the origin address
    distance = directions["routes"][0]["legs"][0]["distance"]["text"]
    # Adds it to the list of distances found from each address
    distances.append(distance)
#print distances
print(*distances, sep="\n")
instead of having a list destinations, it should loop through the csv file addresses
 
    