JSFiddle - React, Tailwind, and code Playground
by jamstooks
HTML
<label for='date'>Date</label>
<input type='text' id='date' value='2013-04-20' /><br/>
<label for='lat'>Latitude</label>
<input type='text' id='lat' value='41.424'/><br/>
<label for='lng'>Longitude</label>
<input type='text' id='lng' value='-71.439'/><br/>
<label for='lng'>Local Timezone Offset</label>
<input type='text' id='offset' value='-4'/><br/>
<label for='zenith'>Zenith</label>
<select id='zenith'>
<option value='90'>Official</option>
<option value='96'>Civil</option>
<option value='102'>Nautical</option>
<option value='108'>Astronomical</option>
</select><br/>
<button type='button' onclick='calculateSunriseSunset();'>Caclulate</button>
<div id='resultsDiv'></div>
JavaScript
/*
Sunrise/Sunset Algorithm
from: http://williams.best.vwh.net/sunrise_sunset_algorithm.htm
inputs:
date: javascript Date object
latLng: array(lat,lng)
zenith: offical, civil, nautical, astronomical
*/
var format = d3.time.format("%Y-%m-%d");
var calculateSunriseSunset = function() {
var d = format.parse(d3.select("#date").attr("value"));
var lat = parseFloat(d3.select("#lat").attr("value"));
var lng = parseFloat(d3.select("#lng").attr("value"));
var zSelect = d3.select("#zenith").node();
console.log(zSelect.options);
var z = parseInt(zSelect.options[zSelect.selectedIndex].value);
// local offset could be calculated with the Google TimeZone API or others
var o = parseInt(d3.select("#offset").attr("value"));
var c = new Calculator(d, lat, lng, z, o);
c.logValues();
c.getLocalTime();
var div = d3.select("#resultsDiv");
div.html("rise: " + c.rLocalTime + " set: " + c.sLocalTime);
};
var Calculator = function(date, lat, lng, zenith, localOffset) {
this.date = date;
this.lat = lat;
this.lng = lng;
this.zenith = zenith;
this.localOffset = localOffset;
this.logValues = function() {
console.log("date: " + this.date);
console.log("lat: " + this.lat);
console.log("lng: " + this.lng);
console.log("zenith: " + this.zenith);
console.log("localOffset: " + this.localOffset);
};
this.getDayOfYear = function() {
var onejan = new Date(this.date.getFullYear(),0,1);
this.dayOfYear = Math.ceil((this.date - onejan) / 86400000);
};
this.getLngHourValue = function() {
this.lngHour = this.lng / 15;
};
this.getApproximateTime = function() {
this.getDayOfYear();
this.getLngHourValue();
this.rApproximateTime = this.dayOfYear + ((6 - this.lngHour) / 24);
this.sApproximateTime = this.dayOfYear + ((18 - this.lngHour) / 24)
};
...