|
| 1 | +from geopy.distance import geodesic |
| 2 | + |
| 3 | + |
| 4 | +def calculate_distance_and_time(coord1, coord2, avg_speed): |
| 5 | + """ |
| 6 | + Calculate the distance between two coordinates and estimate travel time. |
| 7 | + :param coord1: Tuple containing the latitude and longitude of the first location (lat1, lon1) |
| 8 | + :param coord2: Tuple containing the latitude and longitude of the second location (lat2, lon2) |
| 9 | + :param avg_speed: Average speed in km/h for estimating travel time |
| 10 | + :return: Distance in kilometers and estimated travel time in hours |
| 11 | + """ |
| 12 | + |
| 13 | + # Calculate geodesic distance |
| 14 | + distance = geodesic(coord1, coord2).kilometers |
| 15 | + # Estimate travel time (distance / speed) |
| 16 | + travel_time = distance / avg_speed |
| 17 | + |
| 18 | + return distance, travel_time |
| 19 | + |
| 20 | + |
| 21 | +def main(): |
| 22 | + # Coordinates (latitude, longitude) |
| 23 | + try: |
| 24 | + coord1 = tuple(map(float, input('Enter the latitude and longitude of the first location (lat1, lon1) Example: 40.7128, -74.006: ').split(','))) |
| 25 | + coord2 = tuple(map(float, input('Enter the latitude and longitude of the second location (lat2, lon2) Example: 37.7749, -122.4194: ').split(','))) |
| 26 | + except ValueError as e: |
| 27 | + raise ValueError("Coordinates must be in the format 'lat, lon'") from e |
| 28 | + |
| 29 | + if not all(-90 <= x <= 90 for x in (coord1[0], coord2[0])) or not all(-180 <= x <= 180 for x in (coord1[1], coord2[1])): |
| 30 | + raise ValueError('Invalid coordinates') |
| 31 | + |
| 32 | + # Speed in km/h (e.g., driving speed) |
| 33 | + try: |
| 34 | + avg_speed = float(input('Enter the average speed in km/h Example: 60: ')) |
| 35 | + except ValueError as e: |
| 36 | + raise ValueError('Average speed must be a number') from e |
| 37 | + |
| 38 | + if avg_speed <= 0: |
| 39 | + raise ValueError('Average speed must be greater than 0.') |
| 40 | + |
| 41 | + # Calculate the distance and travel time |
| 42 | + distance, travel_time = calculate_distance_and_time(coord1, coord2, avg_speed) |
| 43 | + |
| 44 | + print(f'Distance between the two coordinates: {distance:.2f} kilometers') |
| 45 | + print(f'Estimated travel time: {travel_time:.2f} hours') |
| 46 | + |
| 47 | + |
| 48 | +if __name__ == '__main__': |
| 49 | + main() |
0 commit comments