To achieve this, we can use the csv module to read the CSV file and the geopy library to calculate the geographic distances and the area of a polygon defined by the points. First, make sure to install the geopy library using pip:
pip install geopy
Now, here's a Python script that reads the input CSV file and calculates the geographic distance or polygon area based on the provided mode:
import sys
import csv
import math
from geopy.distance import geodesic
from shapely.geometry import Polygon
def read_csv(filename):
with open(filename, 'r') as file:
reader = csv.DictReader(file)
coordinates = [tuple(map(float, row['lng'], row['lat'])) for row in reader]
return coordinates
def calculate_distance(coordinates):
if len(coordinates) < 2:
print("Error: At least two points are required to calculate distance.")
sys.exit(1)
distance = 0
for i in range(len(coordinates)):
if i < len(coordinates) - 1:
distance += geodesic(coordinates[i], coordinates[i + 1]).meters
print(f"Total distance: {distance / 1000:.2f} km")
def calculate_area(coordinates):
if len(coordinates) < 3:
print("Error: At least three points are required to calculate the polygon area.")
sys.exit(1)
polygon = Polygon(coordinates)
area = polygon.area
print(f"Polygon area: {area / 1000000:.2f} km²")
def main(mode, csv_file):
if mode not in ('distance', 'area'):
print("Error: Invalid mode, please use either 'distance' or 'area'.")
sys.exit(1)
coordinates = read_csv(csv_file)
if mode == 'distance':
calculate_distance(coordinates)
elif mode == 'area':
calculate_area(coordinates)