develop a distance matrix 2 cities in python

To develop a distance matrix for two cities in Python, you can use the geopy and numpy libraries. Here's an example code snippet:

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

# create geolocator object
geolocator = Nominatim(user_agent="my_app")

# define the two cities
city1 = "New York, USA"
city2 = "London, UK"

# get the latitude and longitude of each city
loc1 = geolocator.geocode(city1)
loc2 = geolocator.geocode(city2)

# calculate the distance between the two cities
distance = geodesic((loc1.latitude, loc1.longitude), (loc2.latitude, loc2.longitude)).km

# create a 2x2 matrix of the distance between the two cities
distance_matrix = np.array([[0, distance], [distance, 0]])

print(distance_matrix)
631 chars
23 lines

This code uses the Nominatim geocoder from geopy to get the latitude and longitude of the two cities. The geodesic function is then used to calculate the distance between the two cities in kilometers. Finally, a 2x2 matrix is created using numpy to store the distance between the two cities.

gistlibby LogSnag