diff --git a/howTo/APIkeys/owmAPIkey.R b/howTo/APIkeys/owmAPIkey.R new file mode 100644 index 0000000000000000000000000000000000000000..4b59fce4e2ef6a2da20d73a75a883176f1b4959c --- /dev/null +++ b/howTo/APIkeys/owmAPIkey.R @@ -0,0 +1,2 @@ +# OpenWeatherMapAPI key +owmAPIkey <- "bda9e4fdac62847c129d8ed3227b7325" \ No newline at end of file diff --git a/howTo/apiOpenWeather.R b/howTo/apiOpenWeather.R new file mode 100644 index 0000000000000000000000000000000000000000..a4801f84522245610d19718156143f5c950356b8 --- /dev/null +++ b/howTo/apiOpenWeather.R @@ -0,0 +1,57 @@ +# Open Weather API + +library(woRkflow) # load workflow package +woRkflow::setup() # load env.R set up the default paths etc + +reqLibs <- c("httr", + "jsonlite", + "knitr", + "tidyr", + "data.table", # data munching + "here", # here + "lubridate", # dates and times + "ggplot2", # plots + "bookdown" # for making reports (should also install knittr etc) +) +# load them +woRkflow::loadLibraries(reqLibs) + +# Load API key from external file - so can restrict access if required +source(paste0(here::here(),'/howTo/APIkeys/owmAPIkey.R')) # OpenWeatherMapAPI key + +# API request ---- + +# Get hourly weather forecast from Open Weather (use '&units=metric' for celsius) +getURL <- paste0("https://api.openweathermap.org/data/2.5/onecall?lat=50.937337&lon=-1.404147&units=metric&exclude=minutely,daily&appid=",owmAPIkey) +response <- httr::GET(getURL) + +openWeatherData <- fromJSON(rawToChar(response$content)) + +str(openWeatherData) + +# forecast - current +currentWeather <- openWeatherData$current # into own data.frame + +# forecast - 48 hours ahead +hourlyWeather <- openWeatherData$hourly # into own data.frame + +# process data ---- + +procTime <- function(x){ + as.POSIXct(x, origin="1970-01-01") # convert unix time +} + +currentWeather[1:3] <- lapply(currentWeather[1:3],procTime) +hourlyWeather[,1] <- lapply(hourlyWeather[1],procTime) +hourlyWeather <- unnest(hourlyWeather, cols = weather) + +# Outputs and util ---- +# What to do with the data & presentation info +# ..$pop = probablility of precipitation + +# Get icons - URLs +icon <- "10d" +iconURL <- paste0("http://openweathermap.org/img/wn/",icon,"@2x.png") +download.file(iconURL,paste0(here::here(),'/howTo/weatherAPI/icons/',icon,'.png'), mode = 'wb') + +message(paste0("The weather now is: ",currentWeather$weather$main, " and the temperature is ",round(currentWeather$temp)," degrees.")) diff --git a/howTo/weatherAPI/Icons/10d.png b/howTo/weatherAPI/Icons/10d.png new file mode 100644 index 0000000000000000000000000000000000000000..62304fded6be1c5cea4a6a353cf336a98bec4c3f Binary files /dev/null and b/howTo/weatherAPI/Icons/10d.png differ