Google Distance Matrix API: How to specify origin-destination pairs?

1.6k views Asked by At

I am using the Python client library for Google Maps API (Github link).

I would like to get the duration_in_traffic figures for the following trips:

  • Address1 to Address2

  • Address2 to Address1

  • Address1 to Address3

  • Address3 to Address1

But the syntax of the Google Distance Matrix API (documentation) is problematic in its presumptuousness. It assumes that the user wants data for all conceivable pairings of origin and destination addresses.

The issue is that the following code (source)...

origins = [Address1, Address2, Address3]
destinations = [Address1, Address2, Address3]

matrix = client.distance_matrix(origins, destinations,
                                        mode="driving",
                                        language="en",
                                        units="imperial",
                                        departure_time=now,
                                        traffic_model="best_guess")

produces nine results (that is, every possible combination of origin-destination pairings), when I only need the previously-stated four.

I realize that I can parse these results to extract only the four durations that I need, but I don't want to needlessly double the execution time of my script by forcing it to download data that I do not want.

I also realize that I can send 4 separate requests to get just the durations that I want (that is, one pairing per request), but I am trying not to surpass the quota for my free, non-premium Distance Matrix API account.

So, is it possible to specify the origin-destination pairings within the same request?

1

There are 1 answers

0
Emma On

If I understood the question correctly I think you can solve it by using a dictionary:

dict_addresses= {Address1:Address2, Address2:Address1, Address1:Address3, Address3:Address1}

db= dict()

for origin in dict_addresses:
    duration_traffic= client.distance_matrix(origin, dict_addresses[origin], mode="driving", language="en", units="imperial", departure_time=now, traffic_model="best_guess")
    db[origin]= duration_traffic
    print (db)

For the last part you need to extract the duration_in_traffic from the Distance Matrix array but you should be getting only the 4 results you actually want.