To calculate the distance between two points using the Google Maps API in Python, you can use the googlemaps
library. Before you begin, make sure you have the library installed. You can install it using:
pip install -U googlemaps
Next, you’ll need a Google Maps API key. You can get one by following the instructions on the Google Cloud Console.
Here’s an example script to calculate the distance between two points using the Google Maps API in Python:
import googlemaps from datetime import datetime # Replace 'YOUR_API_KEY' with your actual API key API_KEY = 'YOUR_API_KEY' gmaps = googlemaps.Client(key=API_KEY) def get_distance(origin, destination): try: # Geocoding the addresses to get latitude and longitude origin_geocode = gmaps.geocode(origin)[0]['geometry']['location'] destination_geocode = gmaps.geocode(destination)[0]['geometry']['location'] # Calculating the distance result = gmaps.distance_matrix( origins=(origin_geocode['lat'], origin_geocode['lng']), destinations=(destination_geocode['lat'], destination_geocode['lng']), mode="driving", departure_time=datetime.now() ) # Extracting the distance from the result distance = result['rows'][0]['elements'][0]['distance']['text'] return distance except Exception as e: print(f"Error: {e}") return None if __name__ == "__main__": # Example addresses (replace with your own) origin_address = "San Francisco, CA" destination_address = "Los Angeles, CA" # Get and print the distance distance_result = get_distance(origin_address, destination_address) if distance_result: print(f"The distance between {origin_address} and {destination_address} is: {distance_result}") else: print("Failed to calculate the distance.")
Replace YOUR_API_KEY
with your actual API key and adjust the origin_address
and destination_address
variables with the addresses you want to calculate the distance between. Note that the addresses should be relatively precise to ensure accurate geocoding.
Keep in mind that the Google Maps API has usage limits, and you may incur charges if you exceed the free tier limits. Always check the Google Maps Platform Pricing for more information.