I am working with C# WebClient and the UriBuilder class, communicating with the Google Distance Matrix API. My program is sending comma-separated latitude,longitude pairs. Things are working properly with one origin and multiple destinations: the destinations values on the query string simply need to be delimited with the bar character, "|":
&destinations=latitude1,longitude1|latitude2,longitude2...
But I would like to get it working with multiple origins, where each origin has its own multiple destinations. Is that possible? Or does the API produce a cartesian product, computing distances for every origin against every destination?
If it is possible, how to coordinate origins[i]
with destinations[i]
on the query string?
Here's an example structure in my C# program (geo-locations obscured):
I need to translate that structure into a format the API would accept on the query string, in a manner that links destinationArray[0]
with origin[0]
and destinationArray[1]
with origin[1]
.
It is possible but the Google Distance Matrix API will give you back more results than you need. So yes, it does produce the cartesian product but you can just extract what you need from the result. There's no other way other than sending a separate request per origin.
The structure of the response is documented here https://developers.google.com/maps/documentation/distance-matrix/overview#distance-matrix-responses
The TLDR version goes as follows:
Request:
origins: o1|o2
destinations: d1|d2
the result will be structured/ordered as in:
{
// stuff removed for brevity
// ...
"rows": [
// row for the first origin (o1)
{
"elements": [
// element for the first destination (d1)
{
// stuff removed for brevity
},
// element for the second destination (d2)
{
// stuff removed for brevity
}
]
},
// row for the second origin (o2)
{
"elements": [
// element for the first destination (d1)
{
// stuff removed for brevity
},
// element for the second destination (d2)
{
// stuff removed for brevity
}
]
},
}
So the rows are sorted according to the order of the origins in the origins
parameter. The elements inside each row are sorted according to the order of the destinations in the destinations
parameter.