Skip to content

Commit

Permalink
feat: add FA Legend function
Browse files Browse the repository at this point in the history
fixes #1
  • Loading branch information
jack-davison committed Jul 18, 2024
1 parent 81e1a5d commit 8ecd0db
Show file tree
Hide file tree
Showing 3 changed files with 145 additions and 0 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Generated by roxygen2: do not edit by hand

export("%>%")
export(addFaLegend)
export(faIcons)
importFrom(magrittr,"%>%")
importFrom(rsvg,rsvg_png)
83 changes: 83 additions & 0 deletions R/faIcons.R
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,86 @@ faIcons <- function(icon = "circle",
}


#' Add a Font Awesome legend to a map
#'
#' Manually specify icons, labels, and colours to add a Font Awesome legend to a
#' map. Useful in conjunction with [faIcons()] to communicate the meaning of
#' icons/colours.
#'
#' @param icons Name of the Font Awesome icons, passed to [fontawesome::fa()]. A
#' full list of available icons can be found using
#' [fontawesome::fa_metadata()].
#' @param labels Labels for each `icon`; should be the same length as `icons`.
#' @param colors Colours to use for each `icon`. If `length(colors) == 1L` it is
#' recycled for all icons. Otherwise should be the same length as `icons`.
#' @param title the legend title; optional.
#' @inheritParams leaflet::addControl
#'
#' @return a [leaflet][leaflet::leaflet-package] widget
#' @export
#'
#' @examples
#' library(leaflet)
#' addFaLegend(
#' map = leaflet(),
#' icons = c("beer", "school"),
#' labels = c("Pub", "University"),
#' colors = c("red", "blue"),
#' title = "Student Hangout"
#' )
addFaLegend <- function(map,
icons,
labels,
colors = "black",
title = NULL,
position = c("topright", "bottomright", "bottomleft", "topleft"),
layerId = NULL,
className = "info legend",
data = leaflet::getMapData(map)) {
position <- match.arg(position)

# format title
html_title <- ""
if (!is.null(title)) {
html_title <- paste0("<div style='margin-bottom:3px'><strong>",
title,
"</strong></div>")
}

assemble_legend_item <-
function(icon, label, color) {
paste0(fontawesome::fa(
icon,
width = "1em",
height = "1em",
fill = color
),
" ",
label)
}

html <-
paste0(html_title,
paste0(
purrr::pmap_vec(
tibble::tibble(
icon = icons,
label = labels,
color = colors
),
assemble_legend_item
),
collapse = "<br>"
),

collapse = "<br>")

leaflet::addControl(
map = map,
html = html,
position = position,
layerId = layerId,
className = className,
data = data
)
}
61 changes: 61 additions & 0 deletions man/addFaLegend.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 8ecd0db

Please sign in to comment.