You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何用GoogleDistance获取多地址的距离与时间?

问题分析与解决方案

你的代码核心问题是每次循环都会覆盖同一个变量:$pickupDistanceAndTime2在每次迭代中被重新赋值,导致前一个Driver的计算结果被丢弃,最终只保留最后一次循环的数据。

修正方案1:用数组存储所有结果

初始化一个空数组,将每个Driver的计算结果存入数组中,避免数据被覆盖:

// 初始化空数组存储所有Driver的距离与时间数据
$allPickupResults = [];

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

    // 将结果存入数组,可使用Driver的ID作为键,方便后续关联
    $allPickupResults[$product->id] = $googlePickupDistanceMatrix->distanceAndTime();
}

// 查看所有结果:dd($allPickupResults);

修正方案2:将结果附加到Driver实例

如果需要直接把距离时间数据和对应的Driver实例绑定,可以给实例添加自定义属性:

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

    // 给Driver实例添加自定义属性存储结果
    $product->pickup_info = $googlePickupDistanceMatrix->distanceAndTime();
}

// 后续使用时,直接从Driver实例获取数据
// foreach ($driver as $d) {
//     echo "Driver {$d->id} 距离:{$d->pickup_info['distance']},耗时:{$d->pickup_info['time']}";
// }

这样就能完整获取所有Driver对应的距离与时间数据,不会出现覆盖丢失的情况。

内容的提问来源于stack exchange,提问作者Emmanuel Iyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:01:06