Created
November 5, 2023 19:12
-
-
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
This file contains 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
#' 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