Modifying an API request from one source to another – can't pull the right information out what am I doing wrong?

huangapple go评论124阅读模式
英文:

Modifying an API request from one source to another - can't pull the right information out what am I doing wrong?

问题

你想提取"travel_time"数据并将其除以60以获取分钟数。你可以在以下部分中添加一些代码来实现这一点:

  1. getCommute: function (api_url) {
  2. var self = this;
  3. fetch(api_url)
  4. .then(self.checkStatus)
  5. .then(json => {
  6. self.travel_time = json.results[0].locations[0].properties[0].travel_time / 60; // 提取travel_time并将其除以60
  7. self.errorMessage = self.errorDescription = undefined;
  8. self.loading = false;
  9. self.updateDom();
  10. })
  11. .catch(e => {
  12. self.errorMessage = payload.error.message;
  13. self.errorDescription = payload.error.description;
  14. self.loading = false;
  15. self.updateDom();
  16. });
  17. },

在这个代码片段中,我添加了一个计算travel_time的部分,并将它除以60以获取分钟数。这应该可以帮助你提取并显示旅行时间的分钟数。希望这对你有所帮助!

英文:

Its been two decades since I took a coding class (and I did not use it after I graduated).

I am setting up a MagicMirror dashboard and found a travel times website (www.traveltime.com) that has an API that should work without having to put a credit card down (like many of the others). There are modules on MagicMirror but none using this site.

Is this possible to do??

The API results are:

  1. {"results":[{"search_id":"Matrix","locations":[{"id":"41.87690559224833,-87.63761648086727","properties":[{"travel_time":917}]}],"unreachable":[]}]}

The code I am trying to use is the following:

  1. Module.register('MMM-Traffic', {
  2. defaults: {
  3. interval: 300000,
  4. showSymbol: true,
  5. firstLine: 'Current duration is {travel_time} mins',
  6. loadingText: 'Loading...',
  7. language: config.language,
  8. mode: 'driving',
  9. days: [0, 1, 2, 3, 4, 5, 6],
  10. hoursStart: '00:00',
  11. hoursEnd: '23:59'
  12. },
  13. start: function () {
  14. console.log('Starting module: ' + this.name);
  15. this.loading = true;
  16. this.internalHidden = false;
  17. this.firstResume = true;
  18. this.errorMessage = undefined;
  19. this.errorDescription = undefined;
  20. this.updateCommute = this.updateCommute.bind(this);
  21. this.getCommute = this.getCommute.bind(this);
  22. this.getDom = this.getDom.bind(this);
  23. if ([this.config.originCoordsLAT, this.config.originCoordsLNG, this.config.destinationCoords, this.config.accessToken].includes(undefined)) {
  24. this.errorMessage = 'Config error';
  25. this.errorDescription = 'You must set originCoordsLAT, originCoordsLNG, destinationCoords, and accessToken in your config';
  26. this.updateDom();
  27. } else {
  28. this.updateCommute();
  29. }
  30. },
  31. updateCommute: function () {
  32. var today = new Date()
  33. var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
  34. var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
  35. var dateTime = date+'T'+time+'-06:00';
  36. let mode = this.config.mode == 'driving' ? 'driving' : this.config.mode;
  37. 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}&app_id=TEXT&api_key=TEXT`);
  38. // only run getDom once at the start of a hidden period to remove the module from the screen, then just wait until time to unhide to run again
  39. if (this.shouldHide() && !this.internalHidden) {
  40. console.log('Hiding MMM-Traffic due to config options: days, hoursStart, hoursEnd');
  41. this.internalHidden = true;
  42. this.updateDom();
  43. } else if (!this.shouldHide()) {
  44. this.internalHidden = false;
  45. this.getCommute(this.url);
  46. }
  47. // no network requests are made when the module is hidden, so check every 30 seconds during hidden
  48. // period to see if it's time to unhide yet
  49. setTimeout(this.updateCommute, this.internalHidden ? 3000 : this.config.interval);
  50. },
  51. getCommute: function (api_url) {
  52. var self = this;
  53. fetch(api_url)
  54. .then(self.checkStatus)
  55. .then(json => {
  56. self.travel_time = ; //this is where whatever I put here, it won't pull the travel_time information. I get undefined, etc. If I put a text or number, it does show that
  57. self.errorMessage = self.errorDescription = undefined;
  58. self.loading = false;
  59. self.updateDom();
  60. })
  61. .catch(e => {
  62. self.errorMessage = payload.error.message;
  63. self.errorDescription = payload.error.description;
  64. self.loading = false;
  65. self.updateDom();
  66. });
  67. },
  68. checkStatus: function (res) {
  69. if (res.ok) {
  70. return res.json();
  71. } else {
  72. return res.json().then(json => {
  73. throw new MMMTrafficError(`API Error - ${json.code}`, json.message);
  74. });
  75. }
  76. },
  77. getStyles: function () {
  78. return ['traffic.css', 'font-awesome.css'];
  79. },
  80. getScripts: function () {
  81. return ['moment.js'];
  82. },
  83. getDom: function () {
  84. var wrapper = document.createElement("div");
  85. // hide when desired (called once on first update during hidden period)
  86. if (this.internalHidden) return wrapper;
  87. // base divs
  88. var firstLineDiv = document.createElement('div');
  89. firstLineDiv.className = 'bright medium mmmtraffic-firstline';
  90. var secondLineDiv = document.createElement('div');
  91. secondLineDiv.className = 'normal small mmmtraffic-secondline';
  92. // display any errors
  93. if (this.errorMessage) {
  94. firstLineDiv.innerHTML = this.errorMessage;
  95. secondLineDiv.innerHTML = this.errorDescription;
  96. wrapper.append(firstLineDiv);
  97. wrapper.append(secondLineDiv);
  98. return wrapper;
  99. }
  100. let symbolString = 'car';
  101. if (this.config.mode == 'cycling') symbolString = 'bicycle';
  102. if (this.config.mode == 'walking') symbolString = 'walking';
  103. // symbol
  104. if (this.config.showSymbol) {
  105. var symbol = document.createElement('span');
  106. symbol.className = `fa fa-${symbolString} symbol`;
  107. firstLineDiv.appendChild(symbol);
  108. }
  109. // first line
  110. var firstLineText = document.createElement('span');
  111. firstLineText.innerHTML = this.loading ? this.config.loadingText : this.replaceTokens(this.config.firstLine)
  112. firstLineDiv.appendChild(firstLineText);
  113. wrapper.appendChild(firstLineDiv);
  114. if (this.loading) return wrapper;
  115. // second line
  116. if (this.config.secondLine) {
  117. secondLineDiv.innerHTML = this.replaceTokens(this.config.secondLine);
  118. wrapper.appendChild(secondLineDiv);
  119. }
  120. return wrapper;
  121. },
  122. replaceTokens: function (text) {
  123. return text.replace(/{travel_time}/g, this.travel_time);
  124. },
  125. shouldHide: function () {
  126. let hide = true;
  127. let now = moment();
  128. if (this.config.days.includes(now.day()) &&
  129. moment(this.config.hoursStart, 'HH:mm').isBefore(now) &&
  130. moment(this.config.hoursEnd, 'HH:mm').isAfter(now)
  131. ) {
  132. hide = false;
  133. }
  134. return hide;
  135. },
  136. });

Text from config file:

  1. {
  2. module: "MMM-Traffic",
  3. position: "top_left",
  4. config: {
  5. accessToken: "12345",
  6. originCoordsLAT: "41.95581649395376",
  7. originCoordsLNG: "-87.87083898397289",
  8. destinationCoords: "41.876602828388485_-87.63840104746535",
  9. firstLine: "{travel_time} mins",
  10. }
  11. },

I really just need to get the "travel_time" data point out and then divide it by 60 to get travel time in minutes.

Any help or guidance would be greatly appreciated!

Thank you,
Jim

答案1

得分: 0

你可以通过以下方式访问你想要的键(问号是可选链的一部分):

  1. self.travel_time = json.results?.[0]?.locations?.[0]?.properties?.[0]?.travel_time;

1: 可选链 (Optional chaining)

英文:

Considering that the API returns exacly as you showed, you can access the key you want by doing this (the question marks are optional chaining)

  1. self.travel_time = json.results?.[0]?.locations?.[0]?.properties?.[0]?.travel_time;

huangapple
  • 本文由 发表于 2023年6月12日 04:54:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76452482.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定