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

Google Maps API请求与异步响应匹配问题求助

解决Google Maps Distance Matrix API请求与异步响应匹配的问题

我来给你几个更可靠的方案,彻底解决请求和响应对应不上的问题,比你现在调整目的地数量的办法靠谱多了:

方案1:利用闭包/块级作用域绑定请求上下文

Google Maps Distance Matrix API的响应结果里,elements数组的顺序和你请求时传入的destinations顺序是严格对应的。你可以把50个目的地拆分成多个25个的批次,然后在每个请求的回调里,通过闭包或者let的块级作用域来保存当前批次的目的地信息,这样响应回来时就能直接关联上。

举个简单的代码示例:

const origin = "你的起点坐标/地址";
const allDestinations = ["目的地1", "目的地2", ..., "目的地50"];
// 把数组拆分成每25个一组
const destinationChunks = [];
for (let i = 0; i < allDestinations.length; i += 25) {
  destinationChunks.push(allDestinations.slice(i, i + 25));
}

// 遍历每个批次发起请求
destinationChunks.forEach((chunk) => {
  // 用let的块级作用域保存当前chunk,确保回调里能拿到正确的批次
  const service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [origin],
      destinations: chunk,
      travelMode: 'DRIVING' // 根据你的需求调整出行方式
    },
    (response, status) => {
      if (status === 'OK') {
        // 这里的chunk就是当前请求对应的目的地批次,直接匹配响应结果
        const elements = response.rows[0].elements;
        elements.forEach((element, index) => {
          const destination = chunk[index];
          const travelTime = element.duration.text;
          console.log(`到${destination}的行程时间:${travelTime}`);
        });
      }
    }
  );
});

方案2:用Promise封装请求,统一管理响应

你可以把每个API请求封装成Promise,这样不仅能更好地处理异步流程,还能在Promise resolve时把请求的批次信息和响应结果一起返回,方便后续统一处理。

示例代码:

function getDistanceMatrixBatch(origin, destinations) {
  return new Promise((resolve, reject) => {
    const service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: destinations,
        travelMode: 'DRIVING'
      },
      (response, status) => {
        if (status === 'OK') {
          // 返回批次信息和响应结果
          resolve({ destinations, response });
        } else {
          reject(new Error(`请求失败:${status}`));
        }
      }
    );
  });
}

// 拆分批次后批量发起请求
const origin = "你的起点坐标/地址";
const allDestinations = ["目的地1", "目的地2", ..., "目的地50"];
const destinationChunks = [];
for (let i = 0; i < allDestinations.length; i += 25) {
  destinationChunks.push(allDestinations.slice(i, i + 25));
}

// 用Promise.all处理所有请求
Promise.all(destinationChunks.map(chunk => getDistanceMatrixBatch(origin, chunk)))
  .then(results => {
    results.forEach(result => {
      const { destinations, response } = result;
      const elements = response.rows[0].elements;
      elements.forEach((element, index) => {
        console.log(`到${destinations[index]}的行程时间:${element.duration.text}`);
      });
    });
  })
  .catch(error => {
    console.error(error);
  });

方案3:给目的地添加唯一标识(进阶)

如果你的目的地需要更精准的关联(比如后续要存入数据库),可以提前给每个目的地添加一个自定义的唯一ID,拆分批次时保留这个ID,响应回来后按顺序匹配ID和结果:

// 给每个目的地添加id
const allDestinationsWithId = [
  { id: 1, address: "目的地1" },
  { id: 2, address: "目的地2" },
  // ... 剩下的48个
];

// 拆分批次时只提取address用于API请求,同时保存对应的id数组
const destinationChunks = [];
const idChunks = [];
for (let i = 0; i < allDestinationsWithId.length; i += 25) {
  const chunk = allDestinationsWithId.slice(i, i + 25);
  destinationChunks.push(chunk.map(item => item.address));
  idChunks.push(chunk.map(item => item.id));
}

// 发起请求时关联对应的id批次
destinationChunks.forEach((chunk, index) => {
  const currentIds = idChunks[index];
  const service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [origin],
      destinations: chunk,
      travelMode: 'DRIVING'
    },
    (response, status) => {
      if (status === 'OK') {
        const elements = response.rows[0].elements;
        elements.forEach((element, idx) => {
          console.log(`ID: ${currentIds[idx]},地址:${chunk[idx]},行程时间:${element.duration.text}`);
        });
      }
    }
  );
});

这些方案的核心都是利用API响应与请求顺序严格对应的特性,再通过闭包、Promise或者自定义标识来绑定请求和响应的上下文,完全不需要靠调整目的地数量来匹配,既可靠又灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:16:26