I am getting really long wait times getting results using googles distance matrix

57 Views Asked by At

I am building a small project to help find locations to a user and give the distance between the two. I found some code using the distancematrix that works like a charm, that is until I started including more locations to find the distance between the user and the locations. The code below worked great for three or four locations, but when it gets to 20 or above it will take up to eight or nine seconds. After spending a few hours reading into others projects utilizing the distance matrix this should not be the case and should be able to produce hundreds of results in seconds. By results I mean the distance from point A to point B, yet I am getting bogged down with only 20 queries.
Am I utilizing the distance matrix in an incorrect way?

Note: $orgin is outside the scope of the loop, but had the user address. Any help or recommendations would be greatly appreciated.

foreach ($AllC as $key=>$item){
     
     echo $item;

 $userQueryResult2 = mysqli_query($conn2, "SELECT id, addressP, cityP, StateP, zipP, milesTravel FROM `Performers` WHERE id = $item"); 
            
while($row = mysqli_fetch_array($userQueryResult2)){

     

    $finaelId = $row['id'];

    $AdP = $row['addressP'];
    $CityP = $row['cityP'];
    $StateP = $row['StateP'];
     $ZipP = $row['zipP'];
    $miles = $row['milesTravel'];
   

     $origin = "$AD.', '.$city.' '.$State.' '.$zip";

   $destination = "$AdP.', '.$CityP.' '.$StateP.' '.$ZipP";
     
 
  $distance_data = file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins='.urlencode($origin).'&destinations='.urlencode($destination).'&key=Hidden');
  
  
   $distance_arr = json_decode($distance_data);
if ($distance_arr->status=='OK') {
    $destination_addresses = $distance_arr->destination_addresses[0];
    $origin_addresses = $distance_arr->origin_addresses[0];
} else {
    //Need to Send to an error page
  echo "<p>The request was Invalid. Please Contact Support</p>";
  exit();
}
   if ($origin_addresses=="" or $destination_addresses=="") {
       //Need to send to an error page
      echo "<p>Destination or origin address not found</p>";
      exit();
   }
      
    
   // Get the elements as array
   $elements = $distance_arr->rows[0]->elements;
   $distance = $elements[0]->distance->text;
   $duration = $elements[0]->duration->text;
   echo "From: ".$origin_addresses."<br/> To: ".$destination_addresses."<br/> Distance: <strong>".$distance ."</strong><br/>";
   echo "Duration: <strong>".$duration."";
     echo "<br>";
        if($distance > $miles){
          array_push($tooFar, $finaelId);
          
          
      } else {
          
         array_push($alldone, $finaelId);
           
      }
    
    
    
}
 
 }
 //}
echo $countall;
exit();

0

There are 0 best solutions below