Skip to content

Instantly share code, notes, and snippets.

@oousmane
Created November 5, 2023 19:12
Show Gist options
  • Save oousmane/afa74bef56c9775022eab6139911f4df to your computer and use it in GitHub Desktop.
Save oousmane/afa74bef56c9775022eab6139911f4df to your computer and use it in GitHub Desktop.
Get sunrise and sunset time for any location and date from sunsetsunrise.io API
#' Get sunrise and sunset time for any location and date from sunsetsunrise.io API
#'
#' @param lon longitude in decimal degree of the location
#' @param lat latitude in decimal degree of the location
#' @param date a date string in 'yyy-mm-dd' format.
#'
#' @return a tibble with sunset/sunrise time, day length, location timezone and date
#' @export
#'
#' @examples
#' Retrieve sunrise/sunset data for Ouagadougou (today)
#' lon <- -0.5336873 # Ouagadougou longitude
#' lat <- 12.357192 # Ouagadougou latitude
#' get_sunrisesunset(lon = lon, lat = lat)
get_sunrisesunset <- function(lon = -0.5336873 , lat = 12.357192, date = NULL){
url <- glue::glue("https://api.sunrisesunset.io/json?lat={lat}&lng={lon}")
if (is.null(date)){
today_is <- lubridate::today()
url <- glue::glue("https://api.sunrisesunset.io/json?lat={lat}&lng={lon}")
} else {
today_is <- date
url <- glue::glue("https://api.sunrisesunset.io/json?lat={lat}&lng={lon}&date={today_is}")
}
res <- httr::GET(url)
if(res$status_code == 200) info <- jsonlite::read_json(url)
sunrise <- info$results$sunrise
sunset <- info$results$sunset
timezone <- info$results$timezone
day_length <- info$results$day_length
tibble::tibble(sunrise, sunset, day_length, timezone, date = today_is)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment