javascript - 使用 API 将基于坐标的 Sunrise/Set 导入 Google Sheet

标签 javascript json google-apps-script google-sheets

我花了大约 5 个小时试图解决这个问题,但在最后一点上遇到了困难。

到目前为止,我已经能够调用 https://sunrise-sunset.org/api返回我需要的所有数据。我遇到的问题是能够解析结果,以便将日出或日落值附加到一个变量,我可以将该变量导出为 google 表格中的结果。

理想情况下,在 google 工作表中,我可以像这样使用自定义函数

A1=SunRiseSet(lat,long,date,type)  

="下午 5:11:12"

我想使用类型来指定函数应该返回什么值(日出或日落)。

这是我目前的代码

function SunRiseSet(lat,long,date,type) {
 var response = UrlFetchApp.fetch("https://api.sunrise-sunset.org/json?lat="+lat+"&lng="+long+"&date="+date);  
  var json = response.getContentText();
  Logger.log(json);

  var data = JSON.stringify(json);
  Logger.log(data);
  var data = json;

  var sunrise = data.sunrise;

  var sunset = data.results.sunset

 type=1; 
  if(type==1){
   return this.sunrise}
  else{
   return this.sunset};
}

我敢肯定这真的很容易,但到目前为止我尝试过的一切都失败了。非常感谢!

最佳答案

下面的修改怎么样?

修改点:

  • sunrise 的值在 data.results.sunrise
  • data.results.sunrisedata.results.sunset 可以通过使用 JSON.parse() 解析来检索。

修改后的脚本如下。

修改后的脚本:

function SunRiseSet(lat,long,date,type) {
  var response = UrlFetchApp.fetch("https://api.sunrise-sunset.org/json?lat="+lat+"&lng="+long+"&date="+date);
  var json = response.getContentText();
  var data = JSON.parse(json);
  var sunrise = data.results.sunrise;
  var sunset = data.results.sunset;
  if (type == 1) {
    return sunrise;
  } else {
    return sunset;
  };
}

用法:

  • 请将 =SunRiseSet(lat,long,date,type) 放入电子表格的单元格中。

例如,

  • 当你想要日出时。
    • 请将 =SunRiseSet(36.7201600,-4.4203400,"2017-12-31",1) 放入电子表格的单元格中。请用双引号将 date 括起来。
  • 当你想要日落
    • 请将 =SunRiseSet(36.7201600,-4.4203400,"2017-12-31") 放入电子表格的单元格中。您可以使用 except for 1type。您也可以像示例一样在不使用 type 的情况下使用。

这些参数来自Sunset and sunrise times API .

引用资料:

如果我误解了你的问题,请告诉我。我要修改。

关于javascript - 使用 API 将基于坐标的 Sunrise/Set 导入 Google Sheet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48040528/

相关文章:

javascript - 在 IE 11 中从 HTTP URL 下载 blob

c# - Json.NET 问题

javascript - 如何使用 ng-repeat 从嵌套 json 对象中检索数据

javascript - 空值应用程序脚本谷歌表单

triggers - 有没有办法在onEdit()中获取单元格的原始值?

javascript - 从数组中检索对象,其中另一个对象与另一个数组匹配

javascript - 使用 dropzone.js 中的 uploadMultiple 时出现错误 : Unexpected field.

javascript - Jquery 鼠标滚轮事件仅适用于 Chrome

javascript - 尝试模拟经验增益

java - JAX-RS 如何以带有字段名称的 Json 形式返回列表