Home > other >  How can I get multiple addresses using GoogleDistance in Laravel?
How can I get multiple addresses using GoogleDistance in Laravel?

Time:10-10

I am trying to use loop to get the distance and time for multiple addresses in Laravel

foreach ($driver as $product) {
    $googlePickupDistanceMatrix = new GoogleDistance(
        $product->current_latitude,
        $product->current_longitude,
        $sendLAT,
        $sendLNG,
    );

    $pickupDistanceAndTime2 = $googlePickupDistanceMatrix->distanceAndTime();
}

the $driver variable contains this

0 => App\Driver {#317 ▶}
1 => App\Driver {#300 ▶}
2 => App\Driver {#281 ▶}

The above code returns a single latitude and longitude for one address, I can't find the others, please help.

CodePudding user response:

You are storing the result of the distance request in a scalar varibale and hence overwriting all the results until you can only see that last one.

foreach ($driver as $product) {
    $googlePickupDistanceMatrix = new GoogleDistance(

        $product->current_latitude,
        $product->current_longitude,
        $sendLAT,
        $sendLNG,
    );

    $pickupDistanceAndTime2[] = $googlePickupDistanceMatrix->distanceAndTime();
// change                  ^^
}

If you get

Array ( [0] => Array ( [0] => 4 [1] => 15 ) 
        [1] => Array ( [0] => 4 [1] => 15 ) 
        [2] => Array ( [0] => 18 [1] => 29 ) 
) 

they are the 3 array occurances holding the 3 results, so do another foreach

foreach ( $pickupDistanceAndTime2 as $dt ){
    echo 'Distance ' . $dt[0] . 'and Time ' . $dt[1] . '<br>';
}
  • Related