The problem -> I need to find out the percentage of overlap between two routes.
Solution tried so far -> I tried passing the origin and destination (along with the key of course) to the following URL
https://maps.googleapis.com/maps/api/directions/json
and parsed the json response accordingly. Here is my code snippet -
$endpoint = 'https://maps.googleapis.com/maps/api/directions/json?origin='.$startLatitude1.','.$startLongitude1.'&destination='.$endLatitude1.','.$endLongitude1.'&key='.$mykey;
$json1 = file_get_contents($endpoint.http_build_query(array())); //array is empty here
$data1 = json_decode($json1);
if ($data1->status === 'OK') {
$endpoint = 'https://maps.googleapis.com/maps/api/directions/json?origin='.$startLatitude2.','.$startLongitude2.'&destination='.$endLatitude2.','.$endLongitude2.'&key='.$mykey;
$json2 = file_get_contents($endpoint.http_build_query(array())); //array is empty here
$data2 = json_decode($json2);
$polyline = array();
if ($data2->status === 'OK') {
$route2 = $data2->routes[0];
foreach ($route2->legs as $leg2) {
foreach ($leg2->steps as $step2) {
$polyline[$step2->polyline->points] = $step2->distance->value;
}
}
}
$overlap = 0;
$totalDistance = 0;
$route1 = $data1->routes[0];
foreach ($route1->legs as $leg1) {
$totalDistance = $leg1->distance->value;
foreach ($leg1->steps as $step1) {
if (array_key_exists($step1->polyline->points, $polyline)) {
$overlap = $overlap + $step1->distance->value;
}
}
}
echo 'Total Distance -> '.$totalDistance;
echo 'Overlap -> '.$overlap.'<br>';
}
So we are first traversing route 1 and storing the polylines as key in an associative array with distance as the value. Next we traverse route 2 and check if polylines from route 2 is already present in the associative array created earlier.
The problem -> This works until and unless the roads are straight. Let's assume there are 4 points - A, B, C, D and all are in a straight line in that order. Person X wants to go from A to D whereas person Y wants to go from B to C. So there is an overlap of B-C. But because the polylines will never match (origin and destination being different for X & Y), my code will not detect any overlap.
Any other way out?