How to pass a list of longitudes and latitudes to Distance matrix API

1,960 views
Skip to first unread message

soumojit kumar

unread,
Jan 17, 2021, 11:34:12 AM1/17/21
to or-tools...@googlegroups.com
Hello All,

 I have a list of nodes' longitudes and latitudes. I want to pass them to the Distance matrix API to get the Driving distance between them. In the example code below:
from __future__ import division
from __future__ import print_function
import requests
import json
import urllib


def create_data():
 
"""Creates the data."""
  data
= {}
  data
['API_key'] = 'YOUR_API_KEY'
  data
['addresses'] = ['3610+Hacks+Cross+Rd+Memphis+TN', # depot
                       
'1921+Elvis+Presley+Blvd+Memphis+TN',
                       
'149+Union+Avenue+Memphis+TN',
                       
'1034+Audubon+Drive+Memphis+TN',
                       
'1532+Madison+Ave+Memphis+TN',
                       
'706+Union+Ave+Memphis+TN',
                       
'3641+Central+Ave+Memphis+TN',
                       
'926+E+McLemore+Ave+Memphis+TN',
                       
'4339+Park+Ave+Memphis+TN',
                       
'600+Goodwyn+St+Memphis+TN',
                       
'2000+North+Pkwy+Memphis+TN',
                       
'262+Danny+Thomas+Pl+Memphis+TN',
                       
'125+N+Front+St+Memphis+TN',
                       
'5959+Park+Ave+Memphis+TN',
                       
'814+Scott+St+Memphis+TN',
                       
'1005+Tillman+St+Memphis+TN'
                     
]
 
return data

def create_distance_matrix(data):
  addresses
= data["addresses"]
  API_key
= data["API_key"]
 
# Distance Matrix API only accepts 100 elements per request, so get rows in multiple requests.
  max_elements
= 100
  num_addresses
= len(addresses) # 16 in this example.
 
# Maximum number of rows that can be computed per request (6 in this example).
  max_rows
= max_elements // num_addresses
 
# num_addresses = q * max_rows + r (q = 2 and r = 4 in this example).
  q
, r = divmod(num_addresses, max_rows)
  dest_addresses
= addresses
  distance_matrix
= []
 
# Send q requests, returning max_rows rows per request.
 
for i in range(q):
    origin_addresses
= addresses[i * max_rows: (i + 1) * max_rows]
    response
= send_request(origin_addresses, dest_addresses, API_key)
    distance_matrix
+= build_distance_matrix(response)

 
# Get the remaining remaining r rows, if necessary.
 
if r > 0:
    origin_addresses
= addresses[q * max_rows: q * max_rows + r]
    response
= send_request(origin_addresses, dest_addresses, API_key)
    distance_matrix
+= build_distance_matrix(response)
 
return distance_matrix

def send_request(origin_addresses, dest_addresses, API_key):
 
""" Build and send request for the given origin and destination addresses."""
 
def build_address_str(addresses):
   
# Build a pipe-separated string of addresses
    address_str
= ''
   
for i in range(len(addresses) - 1):
      address_str
+= addresses[i] + '|'
    address_str
+= addresses[-1]
   
return address_str

  request
= 'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial'
  origin_address_str
= build_address_str(origin_addresses)
  dest_address_str
= build_address_str(dest_addresses)
  request
= request + '&origins=' + origin_address_str + '&destinations=' + \
                       dest_address_str
+ '&key=' + API_key
  jsonResult
= urllib.urlopen(request).read()
  response
= json.loads(jsonResult)
 
return response

def build_distance_matrix(response):
  distance_matrix
= []
 
for row in response['rows']:
    row_list
= [row['elements'][j]['distance']['value'] for j in range(len(row['elements']))]
    distance_matrix
.append(row_list)
 
return distance_matrix

########
# Main #
########
def main():
 
"""Entry point of the program"""
 
# Create the data.
  data
= create_data()
  addresses
= data['addresses']
  API_key
= data['API_key']
  distance_matrix
= create_distance_matrix(data)
 
print(distance_matrix)
if __name__ == '__main__':
  main
()

The list of addresses are given as data['addresses'] = ['3610+Hacks+Cross+Rd+Memphis+TN', # depot
                       '1921+Elvis+Presley+Blvd+Memphis+TN',
                       
'149+Union+Avenue+Memphis+TN',
                       
'1034+Audubon+Drive+Memphis+TN',
                       
'1532+Madison+Ave+Memphis+TN',
                       
'706+Union+Ave+Memphis+TN',
                       
'3641+Central+Ave+Memphis+TN',
                       
'926+E+McLemore+Ave+Memphis+TN',
                       
'4339+Park+Ave+Memphis+TN',
                       
'600+Goodwyn+St+Memphis+TN',
                       
'2000+North+Pkwy+Memphis+TN',
                       
'262+Danny+Thomas+Pl+Memphis+TN',
                       
'125+N+Front+St+Memphis+TN',
                       
'5959+Park+Ave+Memphis+TN',
                       
'814+Scott+St+Memphis+TN',
                       
'1005+Tillman+St+Memphis+TN'
                     
]
In my requirement I have the list of addresses as :
['51.9126906, 5.4531776',
 '52.1103819, 5.0621758',
 '52.9772139, 5.9503333',
 '51.9619791, 5.4355059',
 '52.0471328, 4.4709896',
 '51.8293118, 5.7537348',
 '52.2930523, 4.7664696',
 '52.5943338, 6.2852394',
 '52.5466295, 6.1775219',
 '52.0389369, 4.5107113',
 '52.1047185, 5.0657347',
 '51.9062102, 4.4112974',
 '52.0840442, 4.3264277',
 '51.9793189, 5.98069',
 '52.2936821, 4.7180321',
 '51.7034745, 5.0673999',
 '51.7983089, 5.267824',
 '52.0980521, 5.0636588',
 '52.3431487, 4.8290826',
 '52.095637, 5.0834953',
 '52.0482493, 5.116071',
 '52.43854, 4.82643',
 '52.3431487, 4.8290826',
 '52.2477388, 4.5525421',
 '52.0252319, 4.6187327',
 '51.9193715, 5.4572143',
 '52.0789909, 5.0565243',
 '51.6019496, 4.9919145',
 '52.0766223, 4.9101497',
 '52.6719884, 5.0740646',
 '52.1367186, 4.639392',
 '51.4021412, 6.1328951',
 '52.1215725, 5.0529135',
 '52.0469541, 5.1109368',
 '52.0122415, 5.1130648',
 '52.3251554, 4.922911',
 '52.3282083, 4.9274951',
 '51.996967, 4.3957061',
 '51.868232, 4.5473899',
 '52.0306893, 5.6444244']

What Should I do ?


Soumojit Kumar
FRM (GARP, USA), B.E.E. (JU)
Fellow in Management (PhD), IIM Calcutta
Phone(Mob): +91-7003578304
          

Priidik Vilumaa

unread,
Jan 17, 2021, 1:25:08 PM1/17/21
to or-tools-discuss
Not OR-Tools related.

But do it pairwise. IIRC billing is per distance matrix element anyway, so batching will only save you latency. 

Best,
Priidik

Priidik Vilumaa

unread,
Jan 17, 2021, 1:43:06 PM1/17/21
to or-tools-discuss

Mizux Seiha

unread,
Jan 18, 2021, 3:16:12 AM1/18/21
to or-tools-discuss
If you pass latitude/longitude coordinates, they they will snap to the nearest road. Passing a place ID is preferred. If you do pass coordinates, ensure that no space exists between the latitude and longitude values.
```
origins=41.43206,-81.38992|-33.86748,151.20699
```

And using the python framework:
```python
origins = ["Bobcaygeon ON", [41.43206, -81.38992]]
destinations = [
  (43.012486, -83.6964149),
  {"lat": 42.8863855, "lng": -78.8781627},
]
matrix = self.client.distance_matrix(origins, destinations)
```
https://github.com/googlemaps/google-maps-services-python/blob/5253cbc8b7e47bb1f5c1774b2a30705b158fcd8c/tests/test_distance_matrix.py#L87-L93
Reply all
Reply to author
Forward
0 new messages