R/find_closest_tide_station.R

Defines functions find_closest_site

Documented in find_closest_site

#' Find the closest tide station to an arbitrary latitude/longitude point within the UK.
#'
#' Calls either \code{forecast_list_sites()} or \code{observations_list_sites()} and returns the closest site to any lat long point.
#' @param lat Decimal latitude
#' @param long Decimal longitude
#' @param site_count Number of sites to return. Defaults to 1. Sorted by distance (closest to furthest away).
#' @param cached_sites A \code{data.frame} containing a list of all UK tide stations. The list can be generated by calling \code{get_tidal_stations()}
#' @export
#' @examples
#' find_closest_site(lat = 53.8059821, long = -1.6057714, site_count = 1, cached_sites = NULL)
#'

find_closest_site <- function(lat, long, site_count = 1, cached_sites = NULL) {

  if(!is.null(cached_sites)){
    sites <- cached_sites
  }
  else {
    sites<-get_tidal_stations()
  }

sites_distance <- sites %>%
  dplyr::rowwise() %>%
  dplyr::mutate(distance = geosphere::distGeo(c(longitude, latitude), c(long, lat))) %>%
  dplyr::ungroup() %>%
  dplyr::arrange(distance) %>%
  dplyr::top_n(site_count, -distance)

sites_distance

}
simon-tarr/uk.tides documentation built on March 29, 2020, 9:21 p.m.