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

调用Google Distance Matrix接口时出现undefined offset: 0错误求助

解决Google Distance Matrix API调用中的"undefined offset: 0"错误

Hey, let's figure out why you're getting that undefined offset: 0 error in your GetDrivingDistance function. That error pops up because either $response_a['rows'] is empty, or $response_a['rows'][0]['elements'] doesn't have an index 0—meaning the Google Distance Matrix API isn't returning the data you expect. Here's how to fix this step by step:

常见原因及排查方向

  • API请求本身有问题:可能是你的API密钥无效、请求配额用完、经纬度参数格式错误,或者API返回了错误状态(比如INVALID_REQUEST、OVER_QUERY_LIMIT)。
  • 代理配置错误:你的代码里设置了CURLOPT_PROXYPORT但没指定代理地址(CURLOPT_PROXY),如果你的环境不需要代理,这行反而会导致请求失败;如果需要代理,缺少地址会让curl无法连接。
  • 没有做错误处理:你直接访问rows[0]['elements'][0],但没先确认这些数组键是否存在,也没检查API返回的状态。

修改后的函数代码(带完整错误处理)

public function GetDrivingDistance($lat1, $lat2, $long1, $long2) {
    $data1 = setting::where('id',1)->first();
    $key = $data1->key;

    // 先校验经纬度参数是否为有效数字
    if (!is_numeric($lat1) || !is_numeric($long1) || !is_numeric($lat2) || !is_numeric($long2)) {
        return ['error' => 'Invalid latitude/longitude values'];
    }

    $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins={$lat1},{$long1}&destinations={$lat2},{$long2}&mode=driving&language=pl-PL&key={$key}";
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    // 代理配置:不需要就删除下面两行;需要就补充代理地址
    // curl_setopt($ch, CURLOPT_PROXY, 'your_proxy_ip_address');
    // curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
    
    // 修复SSL验证(原来的设置不安全,建议开启验证)
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    
    $response = curl_exec($ch);

    // 检查curl执行是否出错
    if(curl_errno($ch)){
        $errorMsg = curl_error($ch);
        curl_close($ch);
        return ['error' => "Curl request failed: {$errorMsg}"];
    }
    curl_close($ch);

    // 检查JSON解析是否成功
    $response_a = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return ['error' => 'Failed to parse API response (invalid JSON)'];
    }

    // 检查API返回的整体状态
    if (isset($response_a['status']) && $response_a['status'] !== 'OK') {
        $errorDetail = isset($response_a['error_message']) ? $response_a['error_message'] : 'No details provided';
        return ['error' => "API Error: {$response_a['status']} - {$errorDetail}"];
    }

    // 确认rows和elements存在且不为空
    if (!isset($response_a['rows'][0]['elements'][0])) {
        return ['error' => 'No distance/duration data returned from API'];
    }

    $element = $response_a['rows'][0]['elements'][0];
    // 检查单个路线元素的状态
    if ($element['status'] !== 'OK') {
        $errorDetail = isset($element['error_message']) ? $element['error_message'] : 'No details provided';
        return ['error' => "Route Error: {$element['status']} - {$errorDetail}"];
    }

    // 正常返回数据
    return [
        'distance' => $element['distance']['text'],
        'time' => $element['duration']['text']
    ];
}

关键修改说明

  • 参数校验:先确保经纬度是有效数字,避免传入无效参数导致API报错。
  • 代理修复:要么补全代理地址,要么删除不必要的代理配置,避免请求失败。
  • 安全优化:修复了SSL验证设置(原来的0会跳过安全验证,存在风险)。
  • 多层错误处理:依次检查curl请求、JSON解析、API状态、数据结构,每一步都有错误返回,能快速定位问题。
  • 避免数组越界:在访问rows[0]和elements[0]之前,先确认这些键存在,彻底解决undefined offset错误。

内容的提问来源于stack exchange,提问作者rea spider

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 10:27:44