R/map.R

#' Map Earthquakes
#'
#' A simple function that maps and annotates the NOAA significant earthquakes data.
#'
#' @importFrom leaflet leaflet
#' @importFrom leaflet addTiles
#' @importFrom leaflet addCircleMarkers
#' @importFrom magrittr %>%
#'
#' @param data R dataframe corresponding to the NOAA significant earthquakes dataset
#' @param annot_col The column name (as string) to be used in order to annotate each data point
#'
#' @return An annotated leaflet map
#'
#' @export
#'
#' @examples
#' \dontrun{eq_data <- readr::read_delim('signif.txt', delim = '\t')}
#' \dontrun{
#'     eq_data %>%
#'         eq_clean_data() %>%
#'         dplyr::filter(COUNTRY == 'MEXICO' & lubridate::year(DATE) >= 2000) %>%
#'         eq_map(annot_col = 'DATE')
#' }
#'
eq_map <- function(data, annot_col) {
    leaflet::leaflet() %>%
        leaflet::addTiles() %>%
        leaflet::addCircleMarkers(data = data,
                                  lng = ~ LONGITUDE,
                                  lat = ~ LATITUDE,
                                  radius = ~ EQ_PRIMARY,
                                  popup = ~ get(annot_col))
}


#' Create Label for the Map
#'
#' This function takes the dataset as an argument and creates an HTML label that can be used
#' as the annotation text in the leaflet map. The annotation text shows the cleaned location,
#' the earthquakes magnitude and the total number of deaths.
#'
#' @inheritParams eq_map
#'
#' @return String vector containing text annotation for each observation
#'
#' @importFrom stringr str_c
#' @importFrom magrittr %<>%
#'
#' @export
#'
#' @examples
#' \dontrun{eq_data <- readr::read_delim('signif.txt', delim = '\t')}
#' \dontrun{
#'     eq_data %>%
#'         eq_clean_data() %>%
#'         dplyr::filter(COUNTRY == 'MEXICO' & lubridate::year(DATE) >= 2000) %>%
#'         dplyr::mutate(popup_text = eq_create_label(.)) %>%
#'         eq_map(annot_col = 'popup_text')
#' }
#'
eq_create_label <- function(data) {
    data %<>% eq_location_clean()
    t_deaths <- data$TOTAL_DEATHS %>% as.integer()
    t_deaths <- ifelse(is.na(t_deaths),
                       '',
                       stringr::str_c('<b>', 'Total deaths:', '</b> ', t_deaths))
    location <- data$LOCATION_NAME
    location <- ifelse(is.na(location),
                       '',
                       stringr::str_c('<b>', 'Location:', '</b> ', location))
    magnitude <- data$EQ_PRIMARY %>% as.numeric()
    magnitude <- ifelse(is.na(magnitude),
                        '',
                        stringr::str_c('<b>', 'Magnitude:', '</b> ', magnitude))
    stringr::str_c(location, magnitude, t_deaths, sep = '<br>')
}
blnash508/EarthquakesNOAA documentation built on May 14, 2019, 5:25 p.m.