适配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()取整保证显示整数分钟
额外优化建议
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}`);错误处理修复:
原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
相关产品推荐
相关产品推荐

