Skip to content
Snippets Groups Projects
Commit 555fad1c authored by Tom Rushby's avatar Tom Rushby
Browse files

open weather API implementation (WIP)

parent 06c054a7
No related branches found
No related tags found
No related merge requests found
# OpenWeatherMapAPI key
owmAPIkey <- "bda9e4fdac62847c129d8ed3227b7325"
\ No newline at end of file
# 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."))
howTo/weatherAPI/Icons/10d.png

2.52 KiB

0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment