Skip to content

Instantly share code, notes, and snippets.

@mumrah
Created April 11, 2014 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mumrah/10488740 to your computer and use it in GitHub Desktop.
Save mumrah/10488740 to your computer and use it in GitHub Desktop.
Javascript to get temperature, humidity, precipitation, wind, and solr radiation from Weather Underground "history" API
function get_weather_history(year, month, day, query, apikey) {
if(month < 10) {
month = "0" + month;
}
if(day < 10) {
day = "0" + day;
}
var ymd = year + "" + month + "" + day;
var url = "http://api.wunderground.com/api/" + apikey + "/history_" + ymd + "/q/" + query + ".json";
Logger.log("Calling URL: " + url);
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var avg_temp = data['history']['dailysummary'][0]['meantempi'];
var precip_in = data['history']['dailysummary'][0]['precipi'];
if(precip_in == "T") { // TODO what does this mean?
precip_in = "0.00";
}
var max_temp = data['history']['dailysummary'][0]['maxtempi'];
var min_temp = data['history']['dailysummary'][0]['mintempi'];
var gdd = data['history']['dailysummary'][0]['gdegreedays'];
var hdd = data['history']['dailysummary'][0]['heatingdegreedays'];
var cdd = data['history']['dailysummary'][0]['coolingdegreedays'];
var wind = data['history']['dailysummary'][0]['meanwindspdi'];
var humidity = data['history']['dailysummary'][0]['humidity'];
var min_humidity = data['history']['dailysummary'][0]['minhumidity'];
var max_humidity = data['history']['dailysummary'][0]['maxhumidity'];
// Calculate the solar radiation in Joules/m^2 given Watt/m^2
var t0, t1;
var sr0, sr1;
var t0 = 0; // midnight
var sr0 = 0; // no radiation at midnight
var srtotal = 0.0;
// Numerically integrate individual observations
data['history']['observations'].forEach(function(observation) {
// Convert times to seconds since 1 Joule = 1 Watt*second
t1 = parseInt(observation['date']['hour'], 10)*60*60 + parseInt(observation['date']['min'], 10)*60; // seconds
sr1 = parseFloat(observation['solarradiation']);
srtotal += (t1-t0) * ((sr1 + sr0)/2.0); // Trapezoid rule (thanks, grad school!)
t0 = t1;
sr0 = sr1;
});
var sr_MJ = srtotal / 1000000.0; // Guess that physics degree paid off finally
return [parseFloat(min_temp),
parseFloat(avg_temp),
parseFloat(max_temp),
parseFloat(precip_in),
sr_MJ,
parseFloat(wind),
parseFloat(min_humidity),
parseFloat(humidity),
parseFloat(max_humidity)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment