Last active
May 11, 2020 20:00
-
-
Save tsamb/f7ba8f96e8bf8d9dbfc43482f2415c4a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function PRECIPITATION_YESTERDAY() { | |
var ss = SpreadsheetApp.getActiveSpreadsheet(); | |
var rainfallSheet = ss.getSheetByName("Brooklyn daily rainfall"); | |
var hourlyWeatherSheet = ss.getSheetByName("Brooklyn hourly weather"); | |
// DEPENDENCY: Assumes worksheets exist with the above to names. | |
var endpoint = "https://api.openweathermap.org/data/2.5/onecall/timemachine"; | |
var unixTimeYesterday = Math.floor((new Date((new Date).setDate(((new Date).getDate() - 1)))).valueOf() / 1000); | |
// Sign up for an OpenWeatherMap account and then navigate to https://home.openweathermap.org/api_keys | |
// to generate an API key. The free tier allows for 1,000 API calls per day across a selection of endpoints. | |
var queryParams = { | |
"lat": "40.6560831", // coords for Prospect Park | |
"lon": "-73.9653906", // replace with your coords | |
"dt": unixTimeYesterday, | |
"units": "imperial", | |
"appid": "YOUR_OPENWEATHERMAP_APP_KEY_HERE" // replace with your OpenWeatherMap API key | |
}; | |
var queryString = Object.keys(queryParams).map( | |
function(key) { return key.toString() + "=" + queryParams[key] } | |
).join("&"); | |
var response = UrlFetchApp.fetch(endpoint + "?" + queryString); | |
var data = JSON.parse(response); | |
var mmRain = data.hourly.reduce((sum,hour) => { | |
if (hour["rain"] && hour["rain"]["1h"]) { | |
return sum + hour["rain"]["1h"] | |
} else { | |
return sum | |
} | |
}, 0); | |
var hourlyData = data.hourly.map(hour => { | |
var rain; | |
if (hour["rain"] && hour["rain"]["1h"]) { rain = hour["rain"]["1h"] } | |
return [ | |
readable_date(hour.dt), | |
readable_date(hour.sunrise), | |
readable_date(hour.sunset), | |
hour.temp, | |
hour.feels_like, | |
hour.dew_point, | |
hour.humidity, | |
hour.clouds, | |
rain, | |
hour.pressure, | |
hour.wind_deg, | |
hour.wind_gust, | |
hour.wind_speed, | |
data.lat, | |
data.lon | |
]; | |
}); | |
rainfallSheet.appendRow([readable_date(data.current.dt), mmRain]); | |
hourlyData.forEach(row => hourlyWeatherSheet.appendRow(row)) | |
} | |
function readable_date(date) { | |
return new Date(date * 1000).toISOString().replace("T", " ").replace("Z", ""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment