2

I have a csv file with the following format

Tampa Florida, Aarhus Denmark, Tampa Florida
Tampa Florida, Aarhus Denmark, London England, Tampa Florida

Each row is a trip and I need to calculate the total distance traveled from each trip. I figured I could geocode each location for lat/long coordinates then use those coordinate to calculate distance using vincenty in geopy. I need the distance in both miles and kilometers and I need it to write to the csv file with miles in 1 column and kilometers in a separate column.

Tampa Florida, Aarhus Denmark, Tampa Florida, XXX miles, XXX kilometers

I have the following code so far and have spent two days researching for a solution and I guess I am just not a very good programmer so please help:

from geopy.geocoders import ArcGIS
geolocator = ArcGIS()
import csv
with open('ttest.csv', "rb") as infile:
   reader = csv.reader(infile, delimiter=",")
   for row in reader:
      a=",".join(row)
      address, (latitude, longitude)=geolocator.geocode(a, timeout=10)
      print (address, latitude, longitude)

Example of what I am trying to eventually accomplish though it doesn't work.

list1 = ["Tampa, Florida", "Aarhus, Denmark"]
locations = list1
location = geolocator.geocode("locations", timeout=10)
print((location.latitude, location.longitude))
from geopy.distance import vincenty
x = list1[0]
y = list1[1]
Sum all distances in a row
print(vincenty(sum).miles)
print(vicenty(sum).kilometers)

I appreciate any and all help.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
zackusf
  • 21
  • 1

1 Answers1

0

I think that should solve your Problem. If you have further questions don't hesitate to ask.

import csv
from geopy.geocoders import ArcGIS
from geopy.distance import vincenty

geolocator = ArcGIS()

# data to write in file
new_rows_list = []

# read file and generate data to write back
with open('ttest.csv') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        trip = list(map(lambda x: geolocator.geocode(x), row))

        distanceKm = sum(list(map(lambda x, y: vincenty(x.point, y.point).km, trip[:-1], trip[1:])))
        distanceMiles = sum(list(map(lambda x, y: vincenty(x.point, y.point).miles, trip[:-1], trip[1:])))

        row.append(distanceKm)
        row.append(distanceMiles)

        new_rows_list.append(row)

# write back to file
with open('ttest.csv', newline='', mode='w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(new_rows_list)
Paul
  • 500
  • 3
  • 8