distance matrix to show the distance between each pair of cities in python

To get the distance between each pair of cities, we can use the Google Maps API along with geocoding to get the latitude and longitude of each city. We can then use those coordinates to calculate the distance between them using the Haversine formula. Finally, we can store this information in a matrix to visualize the distances between each city.

Here's some Python code that demonstrates this approach:

main.py
import googlemaps
from math import radians, sin, cos, sqrt, atan2

# Your Google Maps API key
gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Dictionary of cities and their locations
cities = {
    'New York City': (40.7128, -74.0060),
    'Los Angeles': (34.0522, -118.2437),
    'Chicago': (41.8781, -87.6298),
    'Houston': (29.7604, -95.3698),
    'Philadelphia': (39.9526, -75.1652)
}

# Function to calculate the distance between two coordinates
def distance(coord1, coord2):
    lat1, lon1 = coord1
    lat2, lon2 = coord2
    R = 6371  # Radius of the earth in km
    dlat = radians(lat2 - lat1)
    dlon = radians(lon2 - lon1)
    a = sin(dlat/2) * sin(dlat/2) + cos(radians(lat1)) \
        * cos(radians(lat2)) * sin(dlon/2) * sin(dlon/2)
    c = 2 * atan2(sqrt(a), sqrt(1-a))
    d = R * c  # Distance in km
    return d

# Create a distance matrix
matrix = {}
for city1 in cities:
    row = []
    for city2 in cities:
        coord1 = cities[city1]
        coord2 = cities[city2]
        dist = distance(coord1, coord2)
        row.append(dist)
    matrix[city1] = row

# Print the distance matrix
for city1 in cities:
    print(city1, matrix[city1])
1167 chars
43 lines

This code uses the Google Maps API and geocoding to get the latitude and longitude of each city in the cities dictionary. It then calculates the distance between each pair of cities using the distance function, which implements the Haversine formula. Finally, the distances are stored in a dictionary called matrix, where the keys are the names of the cities and the values are lists of distances to all other cities.

gistlibby LogSnag