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

如何生成Google Directions API所需的途经点数组格式?

解决方案:将分隔字符串转换为Google Directions API途经点数组

其实不用模板字符串绕弯子,直接用JavaScript的数组原生方法就能轻松搞定,步骤非常清晰:

  1. 先把你的locations字符串按&&拆分成单个位置的数组
  2. 遍历这个数组,把每个位置转换成符合API要求的对象(包含location和stopover属性)
  3. 最终得到的数组就是你需要的wp[0]格式

完整代码示例

var locations = "oradea, ro&&bistrita, ro&&targu frumos, ro";
// 第一步:拆分字符串,得到单个位置的数组
var locationList = locations.split('&&');
// 第二步:将每个位置转换为API要求的对象结构
var waypoints = locationList.map(function(location) {
  return {
    location: location.trim(), // 加trim处理可能存在的多余空格
    stopover: true
  };
});
// 组装成你需要的wp数组结构
var wp = [waypoints];

为什么不推荐用模板字符串?

如果用模板字符串生成对象字符串,后续还要把字符串转成真正的JS对象——要么用不安全的eval,要么得把单引号转双引号再用JSON.parse,反而多了不必要的步骤,直接创建对象才是最安全、最直观的方式。

最终结果验证

wp[0]的结构会完全符合Google Directions API的要求:

[
  { location: 'oradea, ro', stopover: true },
  { location: 'bistrita, ro', stopover: true },
  { location: 'targu frumos, ro', stopover: true }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:21:40