Utilize API to import sunrise and sunset times based on specific coordinates directly into a Google Sheet

After countless hours of trying to crack this code, I’m faced with a final hurdle. The challenge lies in parsing the output from the and storing either the sunrise or sunset time into a variable that can be exported as a result in a Google Sheet.

The ultimate goal is to create a custom function in the Google Sheet that can be utilized like any other formula:

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

This should yield a result like "5:11:12 PM". The ‘type’ parameter is included to specify whether to return the sunrise or sunset value.

Here’s an excerpt of the existing code:

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};
}

While it might seem straightforward, my attempts at solving this have hit a dead end. Your assistance would be greatly appreciated! Thank you!

Answer №1

What do you think about these changes?

Points of Modification :

  • The value of sunrise can be found at data.results.sunrise.
  • To retrieve data.results.sunrise and data.results.sunset, parsing using JSON.parse() is necessary.

The adjusted script reflecting the above points looks like this:

Adjusted Script :

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;
  };
}

Usage :

  • Add =SunRiseSet(lat,long,date,type) to a cell in the spreadsheet.

For instance,

  • To get sunrise:
    • Add
      =SunRiseSet(36.7201600,-4.4203400,"2017-12-31",1)
      to a cell in the spreadsheet. Remember to enclose date in double quotes.
  • For sunset:
    • Add
      =SunRiseSet(36.7201600,-4.4203400,"2017-12-31")
      to a cell in the spreadsheet. You can omit the type parameter or use any value other than 1. You may also follow the sample format without the type.

These parameters are sourced from the API for Sunset and Sunrise Times.

References :

If I have misunderstood your query, please let me know. I am open to making further adjustments.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on building a REST API with Node.js Express.js and OracleDB to perform database updates

Looking for assistance with creating an API in Node.js to fetch and update data on the frontend. I am able to retrieve data using the provided code, but facing challenges updating it. React.js is being used for the frontend. var express = require("expr ...

Retrieve JSON data from a PHP script to be used in an Angular scope

I am attempting to retrieve JSON data from a PHP file to use in an Angular controller. I have used json_encode(pg_fetch_assoc($result)); within the PHP file and when I check with console.log($scope.contents); in the Angular controller, the JSON data is ret ...

Error message when using Vue Global Filter: Value undefined is not defined

Trying to format currency, I initially attempted to use a global filter in Vue: Vue.filter('formatMoney', (val) => { if (!value) return '' val = val.toString() return val.replace(/\B(?=(\d{3})+(?!\d))/g, ",") ...

Objects that are included into an array will end up with an undefined value

Currently, I am in the process of coding a command for my Discord bot that involves adding items to an array of objects stored within a JSON file. To achieve this functionality, I have implemented the following code snippet: let rawdata = fs.readFileSync(& ...

Experiencing difficulties with certain npm CLI modules when using it as a task runner and build tool

After coming across an article about using npm as a build tool, I decided to give it a try for my tasks. However, I am facing an issue that has me stuck. Whenever I run a global command-line tool like JSLINT, JSHINT, or ESLINT using npm, the console always ...

Categorize messages based on the date they were last read in Angular

I am looking to organize my chat application messages by date, similar to the layout in Microsoft Teams app. Here is an example of the message data: [ { "id": 577, "source": { "userID": 56469, ...

Unable to get the code for automatically refreshing a DIV every 5 seconds to function properly

My Inquiry Regarding DIV Refresh I am having issues with the code below that is supposed to automatically refresh the DIV id refreshDiv every 5 seconds, but it is not working as expected. <div id ="refreshDiv" class="span2" style="text-align:left;"&g ...

Step-by-step guide to start an AngularJs application using TypeScript

I have developed an AngularJS App using TypeScript The main app where I initialize the App: module MainApp { export class App { public static Module : ng.IModule = angular.module("mainApp", []) } } And my controller: module MainApp { exp ...

Can ChatGPT Service Error be resolved?

I tried using chatGPT to help me with my HTML code, but every time I opened it I received an error message saying "Failed to get service" Here is the code that I want to make work: <html> <head></head> <body> <script& ...

When using jQuery AJAX to Like/Dislike, a 500 (Internal Server Error) is returned, but the functionality works correctly upon reloading the

My website has a feature where users can press a Like Status button that uses AJAX to send data to the controller. When the button is clicked, it changes from "like" to "dislike" and all associated classes and form actions are updated accordingly. The is ...

Learn how to efficiently import data into d3.js from several JavaScript arrays, and create a dynamically updating chart without the need to refresh the page

I currently have two arrays: one is a list of numbers called nums, and the other is a list of strings titled places. For example: nums=[1,2,3,4,5] places = ["house","gym", "work", "school", "park"] Both arrays are the same length. I am looking to crea ...

Concerns with JavaScript Scope

I'm currently working on a function that I need help with. The function seems pretty straightforward to me: function CheckFile(path){ var status = false; $.ajax({ url: "http://mydomain.com/"+path, type: "HEAD", s ...

Complete a form when a link or button on the webpage is clicked

I have a variety of links and buttons on my webpage, and they are generated dynamically. I am unable to assign an onclick event to each one individually. My goal is to submit form data to the next page whenever any link or button on the page is clicked. ...

Postal Code Auto-Suggest by Google

I'm attempting to create a unique autocomplete feature for a text box that specifically provides postal codes. To accomplish this, I have followed the guidelines outlined in the documentation found at https://developers.google.com/places/webservice/au ...

Utilize or Bring in an external JavaScript file within Ionic 2

Currently working with Ionic 2 and Typescript Angular 2 and facing an issue. I need to utilize an external JavaScript file located at . How can I import or include this in my project? ...

To properly document the results, I must utilize a button to record the identification of a specific color

I'm working on a code that creates a clickable box which changes colors from black to green to white by going through different shades of green whenever the mouse is clicked. What I now need to do is implement a feature that displays the current shade ...

What steps should be taken to link a frontend program on a separate port to a backend system?

Placing my frontend application in the public folder of a node.js application has allowed me to fetch form-data using the following request: try { await axios.post("/api/v1/contact-form", { name, email, msg, }); } My backend, ru ...

In JavaScript, ensure to directly use the value of a variable when defining an asynchronous function, rather than by reference

Hello there, Let me paint you a picture: for (j = 0; j < btnArr.length; j++) { var btn = document.createElement("button"); btn.addEventListener("click", function() { press(this, j) }, false); div.appendChild(btn); } The issue at hand is t ...

Developing New Arrays from JSON Responses using AngularJS

I have a function linked to the factory for controlling: fac.GetDailyCountersList = function () { return $http.get('/Data/GetDailyCountersList') } Within the controller, this is how the function is invoked: $scope.DailyCounters = null; Dai ...

Leverage JSON data in JavaScript

Having some trouble figuring out how to incorporate JSON values into my JS script. Any assistance would be greatly appreciated as I am still new to this! Below is the snippet of code where I need the values (lat and lon) to be inserted: var map; functio ...