"""
Converts trip data from a CSV file to KML line features with descriptions.
Processes a CSV file containing trip data, creating KML line features where:
- Each line connects start/destination coordinates from a trip record
- Lines are styled with blue coloring and 3-pixel width
- Descriptions contain trip details in HTML format
- Invalid coordinate rows are skipped with error notifications
Expected CSV format (with headers):
'Start Lat', 'Start Long', 'Dest Lat', 'Dest Long', 'Trip Start',
'Trip End', 'Driving Date', 'Days to Stay', 'Driving Time',
'Miles', 'Est. Cost', 'Google Maps Link', 'Directions URL'
See "create_calendar.py" for more info about CSV format.
"""
import csv
import simplekml
def csv_to_kml(input_csv, output_kml):
kml = simplekml.Kml()
with open(input_csv, 'r', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
try:
start_lat = float(row['Start Lat'])
start_lon = float(row['Start Long'])
end_lat = float(row['Dest Lat'])
end_lon = float(row['Dest Long'])
line = kml.newlinestring(name=f"{row['Trip Start']} to {row['Trip End']}")
# Set coordinates (KML uses lon,lat order!)
line.coords = [(start_lon, start_lat), (end_lon, end_lat)]
line.style.linestyle.color = simplekml.Color.blue
line.style.linestyle.width = 3
description = f"""
Trip Details:
Driving Date: {row['Driving Date']}
Days to Stay: {row['Days to Stay']}
Driving Time: {row['Driving Time']}
Distance: {row['Miles']} miles
Estimated Cost: {row['Est. Cost']}
Google Maps Link
Directions URL
]]>
"""
line.description = description
except ValueError as e:
print(f"Skipping row due to invalid coordinates: {e}")
continue
kml.save(output_kml)
print(f"Successfully created KML file: {output_kml}")
# Example usage
# $ python3 csv_to_kml.py 1
# takes input1.csv and produces trips_with_lines1.kml
import sys
n = int(sys.argv[1])
csv_to_kml(f'input{n}.csv', f'trips_with_lines{n}.kml')