Calculating Sunrise / Sunset Times in Javascript

I have time and a given latitude in degrees. Is there any way to calculate sunrise and sunset times in Javascript with this information?

+7
javascript
source share
4 answers

The corresponding code can be found at http://www.esrl.noaa.gov/gmd/grad/solcalc/

You need longitude, latitude and date. It would be useful to indicate whether you want an answer in local or global time. The corrections necessary to obtain true accuracy (and the definition that you use for "sunrise" and "sunset") all play a huge role in the efficiency of the calculation.

If you just want to know "approximately" when the sun is on the same level with the horizon "on the assumption of a spherical earth, circular orbit around the Sun and without atmospheric distortion" - then all shooting approaches something completely controllable. But if you want a real answer, you need to work out about 600 lines of script on this website.

For approximations you can see this earlier answer

+5
source share

SunCalc seems to be doing what you want

SunCalc is a small JavaScript library with a BSD license for calculating the position of the sun, the phases of sunlight (sunrise, sunset, twilight, etc.), the position of the moon and the moon phase for a given location and time

https://github.com/mourner/suncalc

+13
source share

This javascript program

https://github.com/Triggertrap/sun-js

calculates sunrise and sunset times based only on the latitude and longitude of your location, which can be obtained automatically from GPS as follows:

<script> var x = document.getElementById("demo"); function getLocation() {    if (navigator.geolocation) {        navigator.geolocation.getCurrentPosition(showPosition);    } else {        x.innerHTML = "Geolocation is not supported by this browser.";    } } function showPosition(position) {    x.innerHTML = "Latitude: " + position.coords.latitude +    "<br>Longitude: " + position.coords.longitude; } </script> 

It includes a readme file to explain how to use it. It calculates zenith and is very accurate.

+2
source share

Sun-time is sufficient if you use JavaScript as a server-side programming language (Node.js).

 npm install sun-time ; 

Then:

 var sun=require('sun-time'); sun('Tunis') // -> ie : return {rise:"05:00",set:"18:36"} 

for more details

+1
source share

All Articles