Many to many distance matrix in python

I’d like to know how i can make a many-to-many query to calculate de distance in km and driving car option for diffent locations of origin and destination. I have a dataframe in which one column has the latitude and longitude for the origins and the other column has the latitude and longitude for the destinations.

I’ve tried this way, but I didn’t succeed

import openrouteservice

df_result = pd.DataFrame()
client = openrouteservice.Client(key='using_my_key) 
row = 0
for i in range(df.shape[0]):
    city = i
    coords = (city['origin'][i],city['destination'][i])
    routes = client.directions(coords)
    df_result = [city['nota_id'][i], city['origin'][i],city['destination'][i],routes['routes'][0]['summary']['distance']]
    row = row + 1

Thank you!


you can use the matrix endpoint for doing so. Note the limits of the free API token and the restrictions for the matrix endpoint when doing so.

You can find an example in python here. As for how this interfaces correctly with pandas DataFrame, see any pandas tutorial. Note, that the ors expects coordinates in [Lon, Lat]-Format.

Best regards

1 Like

Hi!! Thanks for your answer.
I managed to get the query with the following code, in case anyone else is with the same doubt

Here is my code:

client = openrouteservice.Client(key='my_key') # Specify your personal API key
columns_names = ['nota_id',  'long_ced','lat_ced', 'long_sac','lat_sac',  'Distance']
test_out = pd.DataFrame(columns=columns_names, dtype=object) 
row = 0
for i in test_input['nota_id']:
        nota_id = i
        coords = ((test_input.loc[row,'long_ced'],test_input.loc[row,'lat_ced']),(test_input.loc[row,'long_sac'],test_input.loc[row,'lat_sac']))
        routes = client.directions(coords,  profile='driving-car', units='km')
        test_out.loc[row] = [i, test_input.loc[row,'long_ced'],test_input.loc[row,'lat_ced'],test_input.loc[row,'long_sac'],test_input.loc[row,'lat_sac'], routes['routes'][0]['summary']['distance']]
        row = row + 1
        row = row + 1

Thanks for the help!!


this is still using the directions endpoint - since you only need the distances, I’d strongly recommend you switch to the matrix endpoint.

I am no expert in using pandas DataFrames, but after looking at this thread on the forum and the docs, something like DF.loc([['long_ced', 'lat_ced']]).values().tolist() might work to get a list of starting positions as ors matrix would expect it.

Best regards