calculate a distance matrix 2 cities in python

To calculate a distance matrix between two cities in Python, you can use the geopy library that provides different distance functions. Here's an example code snippet to calculate the distance matrix:

main.py
from geopy.distance import geodesic
import numpy as np

# Define the cities
city1 = (40.7128, -74.0060)  # New York City
city2 = (51.5074, -0.1278)   # London

# Calculate the distance between the cities using the geodesic function
distance = geodesic(city1, city2).km

# Create a distance matrix
distance_matrix = np.zeros((2, 2))
for i, city_from in enumerate([city1, city2]):
    for j, city_to in enumerate([city1, city2]):
        distance_matrix[i][j] = geodesic(city_from, city_to).km

print(distance_matrix)
516 chars
18 lines

Explanation:

  • First, we import the necessary libraries geopy to calculate the distance and numpy to create a matrix.
  • Then, we define two cities using (latitude, longitude) format. In the example, we use New York City and London.
  • Next, we use the geodesic() function to calculate the distance between the two cities in km.
  • Finally, we create a 2x2 distance matrix by looping over the two cities and calculating the distance using geodesic(). The resulting matrix is printed.

Note that you can replace the latitude and longitude coordinates with your desired cities.

gistlibby LogSnag