如何利用Google Directions API返回的排序数组重排点对象数组?
嘿,这个需求我之前做路线规划的时候也碰到过,其实用「映射表」来处理是最高效的方案,不用每次遍历数组找元素,直接O(1)查找就行。我给你分两种最常见的场景讲具体实现:
场景1:API返回的是点位ID的排序数组
假设你给每个点位都加了唯一ID(比如自己定义的id或者Google的place_id),API返回的是排序后的ID列表,那可以这么做:
// 你的原始点位对象数组(每个对象带唯一id) const myLocations = [ { id: 'loc1', name: '公司', lat: 39.9042, lng: 116.4074 }, { id: 'loc2', name: '餐厅', lat: 39.915, lng: 116.403 }, { id: 'loc3', name: '超市', lat: 39.92, lng: 116.41 } ]; // Google Directions API返回的优化后点位ID顺序 const optimizedIdOrder = ['loc2', 'loc3', 'loc1']; // 第一步:先把原始数组转成「ID→点位对象」的映射表 const locationMap = new Map(myLocations.map(loc => [loc.id, loc])); // 第二步:按照API返回的顺序,从映射表里取出对应对象,组成新数组 const sortedLocations = optimizedIdOrder.map(id => locationMap.get(id)); console.log(sortedLocations); // 输出就是完全按优化顺序排列的点位对象数组
场景2:API返回的是Waypoints的索引顺序
这是Google Directions API更常见的返回形式——当你请求optimize:true时,API会返回routes[0].waypoint_order字段,里面是你提交的waypoints数组的优化索引(比如你传了3个途经点,返回的数组是它们的排序索引)。这时候要注意起点和终点的位置:
// 你的原始点位:起点 + 途经点数组 + 终点 const startPoint = { id: 'start', name: '家', lat: 39.89, lng: 116.39 }; const waypoints = [ { id: 'wp1', name: '银行', lat: 39.90, lng: 116.40 }, { id: 'wp2', name: '公园', lat: 39.91, lng: 116.41 }, { id: 'wp3', name: '药店', lat: 39.92, lng: 116.42 } ]; const endPoint = { id: 'end', name: '机场', lat: 39.93, lng: 116.43 }; // Google Directions API返回的优化后途经点索引 const optimizedWaypointIndices = [2, 0, 1]; // 第一步:根据索引重新排序途经点数组 const sortedWaypoints = optimizedWaypointIndices.map(index => waypoints[index]); // 第二步:拼接完整的路线数组(起点 + 排序后的途经点 + 终点) const fullSortedRoute = [startPoint, ...sortedWaypoints, endPoint]; console.log(fullSortedRoute); // 输出就是包含起点、优化途经点、终点的完整路线数组
几个要注意的细节
- 一定要保证映射表的键和API返回的标识完全匹配(比如ID大小写、格式不能错),不然会取不到值返回
undefined。 - 如果你的点位没有唯一ID,也可以用经纬度拼接成字符串当键(比如
${loc.lat.toFixed(6)},${loc.lng.toFixed(6)}),但要注意经纬度的精度问题,避免因为小数位差异匹配失败。 - 如果API返回的顺序里有重复标识(一般不会出现,但特殊场景要考虑),可以根据需求决定是保留重复还是去重。
内容的提问来源于stack exchange,提问作者Multitut
相关产品推荐
相关产品推荐

