R/maps.r

#' Create a leaflet map showing earthquake locations
#' 
#' This function creates a leaflet map plot showing the epicenter of 
#' each earthquake in a dataset. 
#' 
#' @param dataset A dataset generated by eq_clean_data().
#' @param annot_col A string giving the name of a column in dataset. The 
#'                  contents of this will be used to fill in the 
#'                  pop-up window when an earthquake is selected. 
#' 
#' @return This function creates a leaflet map with circles 
#'         representing the epicenters of the earthquakes. The radius of 
#'         each circle is determined by the field EQ_PRIMARY. 
#' 
#' @importFrom leaflet leaflet addProviderTiles addCircleMarkers
#' 
#' @examples
#' eq_data <- eq_clean_data("NOAA_earthquakes.txt")
#' eq_data <- subset(eq_data, Country == "Mexico" & YEAR >= 2000)
#' 
#' eq_map(dataset=eq_data, annot_col = "DATE")
#' 
#' @export
eq_map <- function(dataset, annot_col) {
  dataset$annot_col <- dataset[[annot_col]]

  leaflet::leaflet() %>%
    leaflet::addProviderTiles(leaflet::providers$OpenStreetMap) %>% 
    leaflet::addCircleMarkers(data = dataset, 
                      lng = ~ Longitude, lat = ~ Latitude,
                      fillOpacity = 0.2, radius = ~ EQ_PRIMARY,
                      popup = ~ eval(annot_col), weight = 1)
}

#' Create information for pop-up windows on an earthquake map
#' 
#' This function creates HTML content for the pop-up windows on an 
#' earthquake map. The input to this function should be a data set 
#' generated by the function eq_clean_data(). The window will show 
#' the local location of the earthquake (LocalLocation), the magnitude 
#' (EQ_PRIMARY), and the total death count (TOTAL_DEATHS). 
#' 
#' @param dataset A dataset generated by eq_clean_data().
#' 
#' @return A string containing HTML code to display the location, 
#          magnitude, and number of deaths for each earthquake. If any 
#'         information is missing, the HTML object for that value is 
#'         omitted.
#' 
#' @examples
#' eq_data <- eq_clean_data("NOAA_earthquakes.txt")
#' eq_data <- subset(eq_data, Country == "Mexico" & YEAR >= 2000)
#' eq_data$popup_text <- eq_create_label(eq_data)
#' 
#' eq_map(eq_data, annot_col = "popup_text")
#' 
#' @export
eq_create_label <- function(dataset) {
  ret <- c()

  for(i in seq(nrow(dataset))) {
    loc <- dataset$LocalLocation[i]
    mag <- dataset$EQ_PRIMARY[i]
    tot <- dataset$TOTAL_DEATHS[i]
    
    tmp <- "<div>"
    if(!is.na(loc) && loc != "") {
      tmp <- paste0(tmp,"<div><strong>Location:</strong>",loc,"</div>")
    }
    if(!is.na(mag)) {
      tmp <- paste0(tmp,"<div><strong>Magnitude:</strong>",mag,"</div>")
    }
    if(!is.na(tot)) {
      tmp <- paste0(tmp,"<div><strong>Total deaths:</strong>",tot,"</div>")
    }
    tmp <- paste0(tmp,"</div>")
    ret[i] <- tmp
  }

  return(ret)
}
lmitchell4/earthquake documentation built on May 29, 2019, 3:42 a.m.