如何在JavaScript中转换特定数组格式及解决距离矩阵API问题
问题一:数组格式转换
要把["lat","long","abc","def","abcc","deef"]转换成"lat,long | abc,def | abcc,deef"这种格式,核心是每两个元素为一组拼接,组间用|分隔。直接用循环分组+字符串拼接就能实现:
const originalArray = ["lat","long","abc","def","abcc","deef"]; const groupedResult = []; // 每两个元素为一组遍历 for (let i = 0; i < originalArray.length; i += 2) { // 拼接组内元素,兼容数组长度为奇数的情况 const group = originalArray.slice(i, i + 2).join(','); groupedResult.push(group); } // 用|连接所有组得到最终格式 const formattedString = groupedResult.join(' | '); console.log(formattedString); // 输出: "lat,long | abc,def | abcc,deef"
如果你的需求是类似数组结构的输出,可根据实际场景调整,但通常这种带分隔符的格式都是用于API参数拼接的字符串形式。
问题二:Distance Matrix API 代码问题排查
看你的代码,我发现几个关键问题,帮你逐一修正:
1. 变量重复声明错误
你先写了destinationRequest = [];,后面又用let destinationRequest = ...重复声明,这会触发语法错误,直接移除前面的空声明即可。
2. 箭头函数语法错误
代码里的location =>是HTML转义后的字符,要修正为标准的箭头函数语法location =>。
3. Origins 参数格式不匹配
Google Distance Matrix API要求origins参数是纬度,经度格式,但你直接返回locationDetail,如果locationDetails.origins里的元素是包含lat和long的对象,需要像处理destinations一样拼接成lat,long格式。
4. URL 参数的空格问题
URL里units=imperial &origins=这类位置的空格会导致参数解析失败,必须移除多余空格。
修正后的完整代码
export async function getStoreDistance(locationDetails) { // 生成目标地址参数,去掉重复声明 const destinationRequest = locationDetails.destinations.map(location => { console.log('destreqlocation', location); return `${location.lat},${location.long}`; // 移除末尾多余空格 }); // 处理起点参数,确保符合API格式 const origins = locationDetails.origins.map(locationDetail => { return `${locationDetail.lat},${locationDetail.long}`; }).join('|'); // 多个起点用|分隔,符合API要求 try { const response = await axios.get( `https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=${origins}&destinations=${destinationRequest.join('|')}&key=**********` ); // 返回响应数据,按需调整返回内容 return response.data; } catch (error) { console.error('Distance Matrix API调用失败:', error); // 可根据业务需求处理错误,比如返回错误信息或重新抛出 throw error; } }
额外注意事项
- 确认
locationDetails.origins和locationDetails.destinations的每个对象都有合法的lat、long数值属性。 - 多个起点/终点必须用
|分隔,这是API明确要求的格式。 - 确保你的API密钥已启用Distance Matrix API权限,且未超出调用配额。
内容的提问来源于stack exchange,提问作者Ankit Kumar
相关产品推荐
相关产品推荐

