Message Boards Message Boards

API function: time when the sun is just above a certain altitude

GROUPS:

When you want targeted functionality that just seems like it would be very complicated to fish out of the results from the Wolfram|Alpha API, I would suggest creating your own instant API using Wolfram Language and deploying it to the Wolfram Cloud. In this case, the amount of code you will need it actually quite small.

Let's begin with the function that returns the time of day when the sun is just above a certain altitude. This can be done several ways, but I chose to use the built in functions Sunset and DaylightQ as the main components.

Sunset is a function that can be given a location and it returns the next upcoming sunset time. DaylightQ is a function that when given a location and a time will return if it there is daylight.

sunTime[loc_GeoPosition, alt_]:=
   DateString@TimeZoneConvert[
     NestWhile[DatePlus[# ,{-1, "Minute"}]&, Sunset[loc], !DaylightQ[loc, #, "SunAngleTest" -> (# > alt &)]&],
    LocalTimeZone[loc]]

This function (I creatively called it sunTime), expects a location and an altitude for the sun as input. Once given a location and altitude, it computes the next sunset time (Sunset[loc]) and then starts repeatedly (NestWhile) subtracting in 1 minute (DatePlus[#, {-1, "Minute"}] &). It will keep subtracting 1 minute until my test ( ! DaylightQ[loc, #, "SunAngleTest" -> (# > alt &)] &) fails to be True. Here the test is using a custom "definition" for daylight, which is that the altitude of the sun is greater than alt degrees. Once the test fails, I want to make sure the returned time is in the expected time zone, so I used TimeZoneConvert with LocalTimeZone, and finally DateString so something a bit more human readable is returned.

A quick test of the function (where Here for me is GeoPosition[{40.11, -88.24}]):

sunTime[Here,10]
(* "Tue 10 Jan 2017 15:40" *)

Now to make this an API is very simple. I just use APIfunction and CloudDeploy

CloudDeploy[
  APIFunction[{"loc" -> "Location", "alt" -> "Number"}, sunTime[#loc, #alt]&, "String"],
 "sunTimeAPI", Permissions-> "Public"]

This will result in a CloudObject with a URL inside. Using the API is as simple as making an HTTP request to that URL with the appropriate parameters.

https://www.wolframcloud.com/objects/jhernandez/sunTimeAPI?loc=7.41N+49.23E&alt=2

Feel free to check out this API (the one you create will of course be at a different URL).

POSTED BY: Jesus Hernandez
Answer
10 months ago

enter image description here - you have earned "Featured Contributor" badge, congratulations !

This is a great post and it has been selected for the curated Staff Picks group. Your profile is now distinguished by a "Featured Contributor" badge and displayed on the "Featured Contributor" board.

POSTED BY: Moderation Team
Answer
8 months ago

Group Abstract Group Abstract