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

Strange response received from Stack Overflow API request

Having some issues with the code I'm using to call the Stack Overflow API: var request = require('request'); var url = 'http://api.stackexchange.com/2.2/search?order=desc&sort=activity&tagged=node.js&intitle=node.js&sit ...

Troubleshooting Angular JS Module Injection Issues

Lately, I've been exploring the wonders of angular JS and it has truly impressed me. However, one concept that still eludes my full understanding is injection. Despite this, I have successfully employed this technique across numerous pages in my proje ...

Tips for Developing Drag Attribute Directive in Angular 2.0

Currently, I am referencing the Angular documentation to create an attribute directive for drag functionality. However, it seems that the ondrag event is not functioning as expected. Interestingly, the mouseenter and mouseleave events are working fine ac ...

Comparing the efficiency of Jquery draggable with thousands of elements versus updating the elements continuously

Currently, I am developing an application that involves dragging an image using Jquery's draggable utility. The image is accompanied by several overlay divs containing various components positioned based on pixel locations, sometimes reaching into the ...

Show where the image should be placed according to the coordinates of the mouse click

My project begins with a blank canvas, prompting the user to click anywhere on the page to reveal an image. My goal is to show an image at the exact location where the user clicks. Although I can successfully trigger an image to appear in the corner of the ...

Determining the number of words in every line within a textarea

I am looking to determine the number of words per line in a textarea. The width of the textarea is variable. Check out this code snippet that calculates the number of rows: http://jsfiddle.net/2tcygj9e/ ...

An object-c alternative to encodeURIComponent

Having difficulty finding information on this through a search engine. Is there a similar method in Objective-C for encoding URI components? http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp This is a common task, but I am unable to locate any ...

"Empowering your scripting skills with PowerShell to manipulate JSON data

Greetings everyone, I have been executing a ReST api call in PowerShell and received the following response: $response page content ---- ------- @{size=20; numbe ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Achieving optimal performance with scoped CSS in Vue.js

As I work on creating a new app using VueJs, I have noticed the implementation of "css scoped" as shown below: <style scoped> .example { color: red; } </style> <template> <div class="example">hi</div> </template> ...

Converting Boolean to String representation (Y or N) using GSON serialization

I've been experimenting with this code for Serializing/Deserializing json to gson and vice versa public class CustomBooleanSerializer implements JsonSerializer<Boolean>, JsonDeserializer<Boolean> { @Override public JsonElement ser ...

Transitioning from the Play mode to the Pause mode upon pressing the Set button

Is there a way to make the button switch from play to pause once the 'Set' button is clicked? Clicking on 'Set' should change the SVG to display the pause button icon. Snippet of Code: https://jsfiddle.net/192h0w85/195/ (function ...

The form control is missing a specified name attribute, causing an error with the value accessor

<input type="email" class="form-control passname" [(ngModel)]="emailID" name="Passenger Email ID" placeholder="email" required pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"/> <div class="shake-tool ...

Attempting to extract multiple values from a single-value context using json.Marshal()

Click here to view the following code snippet: package main import ( "fmt" "encoding/json" ) func main() { map1 := map[string]map[string]interface{}{} map2 := map[string]interface{}{} map2["map2item"] = "map2item" map1["map2"] = ...

Personalized FullCalendar header title

Is there a way to display a unique header title for each calendar in my collection of 16? I've been trying various modifications to the code snippet below with no success: firstDay: <?php echo $iFirstDay; ?>, header: { left: 'prev,next ...

Retrieving multiple selected row values using an ASP Repeater

Within my repeater, I have three values bound: a visible "User Name" column, a visible "Business" column, and a hidden field called "UserId". My goal is to implement the following functionality: when a row is clicked, it should highlight in a different c ...

Optimal method for sending FQL response to cakephp controller using jQuery

My FQL result is a JavaScript object with the following structure: [{"name":"3904","fql_result_set":[{"like_count":"0"}]},{"name":"7617","fql_result_set":[{"like_count":"0"}]},{"name":"9674","fql_result_set":[{"like_count":"0"}]}] I am struggling to pass ...

jQuery Ajax comes with a built-in method for validating serialized forms. This method allows

After creating a form and serializing it to send to my MVC Action method, here is how my jQuery Ajax script looks: $('#submit').click(function () { var jsonObj = $('#form').serialize(); alert(jsonObj); $.ajax({ ty ...

Retrieving, storing, and implementing the classes of child elements directly from an array using jQuery

With the help of jQuery, you can retrieve child elements of the #parent element that have the class .west. In this case, we are not interested in fetching the content of these child elements but instead their class names. For example: <div id="parent" ...

There was an issue with the v-on handler: "An error occurred because it was unable to read properties of an undefined value (specifically 'input')."

Can anyone help me? When I click the icon inside the avatar, I want to select a file. But I'm getting an error: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'input'). Could anyone help me? <v-row v-for=" ...