0

I am trying to calculate the driving distance from one origin point and then to many different destinations points (I need to find the closest driver). I use PHP and I basically run this function many times:

file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins=' . $latitude . ',' . $longitude . '&destinations=' . $latitude1 . ',' . $longitude1 . '&mode=car&language=da-DK&key=My_API&alternatives=false&sensor=false');

I need the distance from latitude, longitude and in some cases 40+ different potential destinations. My problem is, that it takes forever to calculate the many points one call at the time. It takes 51-56 sec to find the distance from the one origin point to 37 different potential destination points.

Is there a faster way? or service ?

I wish you all a great day.

best regards

SorenPeter
  • 243
  • 1
  • 4
  • 9

2 Answers2

0

Well, IMO you have 3 possibilities:

1) Stick with php and use pthreads, you may be able to process one request per thread and reduce the time your script is working. Have a look at this

2) go "async" and use one http request per driver, so get a list of drivers first and then send a request for each driver. This would involve there is a frontend capeable of executing javascript (browser)

3) use another technology for this purpose, that is non-blocking, like nodejs. Using promises you could do this easily:

let urls = ["url1", "url2", "url3"];

asnyc doRequest(url) {
    // return promise...
}

Promise.all(urls.map(doRequest)).then(data => {
    console.log(data);
});

Have a look here!

Philipp Wrann
  • 1,751
  • 3
  • 19
  • 29
0

I did start out with the nodejs, and that did also do it. However I managed to find an even smarter way. Efter more intense reading, google can actually you do it for you.

It is posible to enter one origin and multiple destinations. origins=lat,lng&destinations=lat1,lng1|lat2,lng2|...latn,lngn&

simply use | to divide destinations.

I went from 51 seconds to 2 seconds.

SorenPeter
  • 243
  • 1
  • 4
  • 9