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

适配TravelTime API的MagicMirror模块无法提取travel_time值求助

解决TravelTime API travel_time提取问题

核心修改:正确提取嵌套结构中的travel_time

根据你提供的API返回数据结构,travel_time位于多层嵌套的数组和对象中,你需要逐层访问这些结构来获取值。将getCommute函数中的赋值语句修改为:

self.travel_time = Math.round(json.results[0].locations[0].properties[0].travel_time / 60);

代码逻辑说明

API返回的结构层级拆解:

  • json.results:结果数组,取第一个元素[0](你的场景下仅返回一组结果)
  • results[0].locations:目标地点数组,取第一个元素[0](对应配置中的目的地)
  • locations[0].properties:属性数组,取第一个元素[0](包含旅行时间的属性对象)
  • properties[0].travel_time:获取到秒级旅行时间,除以60转换为分钟,用Math.round()取整保证显示整数分钟

额外优化建议

  1. API请求参数修正:
    你当前URL中的app_id=TEXT&api_key=TEXT是占位符,需替换为实际的TravelTime API凭证;同时配置里的destinationCoords用下划线分隔,API要求逗号分隔,需转换:

    this.url = encodeURI(`https://api.traveltimeapp.com/v4/time-filter?type=${mode}&departure_time=${dateTime}&search_lat=${this.config.originCoordsLAT}&search_lng=${this.config.originCoordsLNG}&locations=${this.config.destinationCoords.replace('_', ',')}&app_id=你的实际APP_ID&api_key=${this.config.accessToken}`);
    
  2. 错误处理修复:
    原catch块中使用了未定义的payload,修正为:

    .catch(e => {
      self.errorMessage = e.message;
      self.errorDescription = e.description || '未知错误';
      self.loading = false;
      self.updateDom();
    });
    

修改后的完整getCommute函数

getCommute: function (api_url) {
  var self = this;
  fetch(api_url)
    .then(self.checkStatus)
    .then(json => {
      // 正确提取travel_time并转换为分钟
      self.travel_time = Math.round(json.results[0].locations[0].properties[0].travel_time / 60);
      self.errorMessage = self.errorDescription = undefined;
      self.loading = false;
      self.updateDom();
    })
    .catch(e => {
      self.errorMessage = e.message;
      self.errorDescription = e.description || '未知错误';
      self.loading = false;
      self.updateDom();
    });
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:53:18