diff --git a/.Rbuildignore b/.Rbuildignore index 673811fb5..fa6391680 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -33,5 +33,5 @@ ^revdep$ ^CRAN-SUBMISSION$ ^_dev$ -^vignettes$ +^vignettes/articles$ ^pkgdown$ diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 53fd6e12d..807502ee4 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,4 +1,6 @@ -We welcome contributions to the **leaflet** package! +# Contributing to `{leaflet}` + +We welcome contributions to the `{leaflet}` package! To submit a contribution: diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index eac35cc3a..08c9c9853 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,6 +1,6 @@ -Please briefly describe your problem and what output you expect. If you have a question, please try using stackoverflow first. +Please briefly describe your problem and what output you expect. If you have a question, please try using StackOverflow first. -Please include a minimal reprex. The goal of a reprex is to make it as easy as possible for me to recreate your problem so that I can fix it. If you've never heard of a reprex before, start by reading , and follow the advice further down the page. Do NOT include session info unless it's explicitly asked for, or you've used `reprex::reprex(..., si = TRUE)` to hide it away. Make sure to have `webshot` installed to have `reprex` produces images of the leaflet htmlwidgets. +Please include a minimal reprex. The goal of a reprex is to make it as easy as possible for me to recreate your problem so that I can fix it. If you've never heard of a reprex before, start by reading , and follow the advice further down the page. Do NOT include session info unless it's explicitly asked for, or you've used `reprex::reprex(..., session_info = TRUE)` to hide it away. Make sure to have `webshot` installed to have `reprex` produces images of the leaflet htmlwidgets. ```r # make sure webshot is installed to take pictures of htmlwidgets if (!("webshot" %in% installed.packages()[, "Package"])) { diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 463e21248..7e80eb934 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -21,7 +21,7 @@ We will try to be responsive and provide feedback in case we decide not to merge ## Minimal reproducible example -Finally, please include a minimal reprex. The goal of a reprex is to make it as easy as possible for me to recreate your problem so that I can fix it. If you've never heard of a reprex before, start by reading , and follow the advice further down the page. Do NOT include session info unless it's explicitly asked for, or you've used `reprex::reprex(..., si = TRUE)` to hide it away. Make sure to have `webshot` installed to have `reprex` produces images of the leaflet htmlwidgets. +Finally, please include a minimal reprex. The goal of a reprex is to make it as easy as possible for me to recreate your problem so that I can fix it. If you've never heard of a reprex before, start by reading , and follow the advice further down the page. Do NOT include session info unless it's explicitly asked for, or you've used `reprex::reprex(..., session_info = TRUE)` to hide it away. Make sure to have `webshot` installed to have `reprex` produces images of the leaflet htmlwidgets. ```r # make sure webshot is installed to take pictures of htmlwidgets if (!("webshot" %in% installed.packages()[, "Package"])) { diff --git a/NEWS.md b/NEWS.md index cafde5785..f26b6a67e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -52,7 +52,7 @@ - Enable JS function literals (wrapped in `htmlwidgets::JS()`) to be included in arguments to methods invoked on `leafletProxy` objects. (JS function literals could already be included with methods invoked on `leaflet` objects, so this change just brings `leafletProxy` to parity.) (#420) -- Add missing CSS rule to show `` in right-pane and left-pane (rstudio/rmarkdown/issues#1949, #770) +- Add missing CSS rule to show `` in right-pane and left-pane (rstudio/rmarkdown#1949, #770) - Allow for _hidden_ but not suspended leaflet maps to queue calls (such as add raster images) until they are rendered. If a new leaflet map is created, all pending calls are removed. (#771) @@ -137,7 +137,7 @@ ## Bug fixes and features -- Relative protocols are used where possible when adding tiles (#526). In RStudio 1.1.x on linux and windows, a known issue of 'https://' routes fail to load, but works within browsers (rstudio/rstudio#2661). +- Relative protocols are used where possible when adding tiles (#526). In RStudio 1.1.x on Linux and Windows, a known issue of 'https://' routes fail to load, but works within browsers (rstudio/rstudio#2661). - Added more providers for `addProviderTiles()`: "OpenStreetMap.CH", "OpenInfraMap", "OpenInfraMap.Power", "OpenInfraMap.Telecom", "OpenInfraMap.Petroleum", "OpenInfraMap.Water", "OpenPtMap", "OpenRailwayMap", "OpenFireMap", "SafeCast". (4aea447) @@ -221,7 +221,7 @@ - When used with `leafletProxy`, `fitBounds` did not return its input object as output, so magrittr chains would break after `fitBounds` was called. -- Add addMeasure()/removeMeasure() functions to allow users to measure lines and +- Add `addMeasure()`/`removeMeasure()` functions to allow users to measure lines and areas, via the leaflet-measure plugin by @ljagis. (PR #171. Thanks, Kenton Russell!) diff --git a/R/layers.R b/R/layers.R index d68a9043a..104f7b2fa 100644 --- a/R/layers.R +++ b/R/layers.R @@ -1,7 +1,9 @@ #' Evaluate list members that are formulae, using the map data as the environment -#' (if provided, otherwise the formula environment) +#' +#' Evaluates if provided. Otherwise, the formula environment is evaluated. #' @param list with members as formulae #' @param data map data +#' @keywords internal #' @export evalFormula <- function(list, data) { evalAll <- function(x) { @@ -44,7 +46,9 @@ expandLimits <- function(map, lat, lng) { map } -#' Same as expandLimits, but takes a polygon (that presumably has a bbox attr) +#' Notifies the map of polygons of interest on the map +#' +#' Same as `expandLimits()`, but takes a polygon (that presumably has a bbox attr) #' rather than lat/lng. #' @param map map object #' @param poly A spatial object representing a polygon. @@ -1213,7 +1217,7 @@ markerOptions <- function( #' \code{\{weight: 1.5, color: "#222", opacity: 0.5 \}}. #' @param freezeAtZoom Allows you to freeze cluster expansion to a zoom level. #' Can be a zoom level e.g. 10, 12 or "max" or "maxKeepSpiderify". -#' See . +#' See \url{https://github.com/ghybs/Leaflet.MarkerCluster.Freezable#api-reference}. #' @describeIn map-options Options for marker clusters #' @export markerClusterOptions <- function( diff --git a/R/leaflet-package.R b/R/leaflet-package.R index e6faac196..4f3bf00c6 100644 --- a/R/leaflet-package.R +++ b/R/leaflet-package.R @@ -1,12 +1,9 @@ #' @keywords internal -#' @aliases leaflet-package NULL "_PACKAGE" ## usethis namespace: start #' @importFrom grDevices col2rgb #' @importFrom grDevices rgb -#' @importFrom htmlwidgets JS -#' @importFrom magrittr %>% #' @importFrom methods substituteDirect #' @importFrom stats na.omit #' @importFrom stats quantile @@ -16,9 +13,12 @@ NULL ## Re-exports -#' @export %>% -#' @export JS -NULL +#' @importFrom magrittr %>% +#' @export +magrittr::`%>%` +#' @importFrom htmlwidgets JS +#' @export +htmlwidgets::JS # Added to the `use_release_issue()` checklist release_bullets <- function() { diff --git a/R/leaflet.R b/R/leaflet.R index 3def2b0c7..d67bc1b81 100644 --- a/R/leaflet.R +++ b/R/leaflet.R @@ -103,8 +103,9 @@ hookWrapperTemplate <- "function(el, x, data) { return (%s).call(this.getMap(), el, x, data); }" -#' returns the map's data +#' Extract the map's data #' @param map the map +#' @returns The map's data #' @export getMapData <- function(map) { attr(map$x, "leafletData", exact = TRUE) diff --git a/R/normalize.R b/R/normalize.R index 2c87050ad..ccd4b912e 100644 --- a/R/normalize.R +++ b/R/normalize.R @@ -35,16 +35,22 @@ metaData.data.frame <- function(obj) obj metaData.list <- function(obj) obj -#' Given a data object and lng/lat arguments (which may be NULL [meaning infer -#' from data], formula [which should be evaluated with respect to the data], or +#' Normalize data to a data frame or Spatial object. +#' +#' Given a data object and lng/lat arguments (which may be `NULL`) +#' [meaning infer from data], formula [which should be evaluated with respect to the data], or #' vector data [which should be used as-is]) return a lng/lat data frame. +#' #' @param data map data -#' @param lng longitude -#' @param lat latitude +#' @param lng,lat longitude and latitude #' @param missingLng whether lng is missing #' @param missingLat whether lat is missing #' @param funcName Name of calling function (for logging) +#' @returns +#' * `derivePoints()` returns a lng/lat data frame. +#' * `derivePolygons()` returns a list with bbox attributes. #' @export +#' @keywords internal derivePoints <- function(data, lng = NULL, lat = NULL, missingLng = missing(lng), missingLat = missing(lat), @@ -65,15 +71,7 @@ derivePoints <- function(data, lng = NULL, lat = NULL, validateCoords(lng, lat, funcName) } -#' Given a data object and lng/lat arguments (which may be NULL [meaning infer -#' from data], formula [which should be evaluated with respect to the data], or -#' vector data [which should be used as-is]) return a spatial object -#' @param data map data -#' @param lng longitude -#' @param lat latitude -#' @param missingLng whether lng is missing -#' @param missingLat whether lat is missing -#' @param funcName Name of calling function (for logging) +#' @rdname derivePoints #' @export derivePolygons <- function(data, lng = NULL, lat = NULL, missingLng = missing(lng), diff --git a/R/plugin-awesomeMarkers.R b/R/plugin-awesomeMarkers.R index 76d8c9e5e..a17a7f151 100644 --- a/R/plugin-awesomeMarkers.R +++ b/R/plugin-awesomeMarkers.R @@ -159,13 +159,13 @@ makeAwesomeIcon <- function( structure(icon, class = "leaflet_awesome_icon") } -#' Create a list of awesome icon data see -#' \url{https://github.com/lennardv2/Leaflet.awesome-markers} +#' Create a list of awesome icon data #' #' An icon can be represented as a list of the form \code{list(icon, library, #' ...)}. This function is vectorized over its arguments to create a list of -#' icon data. Shorter argument values will be re-cycled. \code{NULL} values for -#' these arguments will be ignored. +#' icon data. Shorter argument values will be recycled. \code{NULL} values for +#' these arguments will be ignored. +#' @seealso \url{https://github.com/lennardv2/Leaflet.awesome-markers} #' @param icon Name of the icon #' @param library Which icon library. Default \code{"glyphicon"}, other possible #' values are \code{"fa"} (fontawesome) or \code{"ion"} (ionicons). diff --git a/R/plugin-graticule.R b/R/plugin-graticule.R index 931dbca9b..1c34edbfe 100644 --- a/R/plugin-graticule.R +++ b/R/plugin-graticule.R @@ -11,11 +11,11 @@ leafletGraticuleDependencies <- function() { } #' Add a Graticule on the map -#' see \url{https://github.com/turban/Leaflet.Graticule} #' +#' @seealso \url{https://github.com/turban/Leaflet.Graticule} #' @param map a map widget object #' @param interval The spacing in map units between horizontal and vertical lines. -#' @param sphere boolean. Default FALSE +#' @param sphere boolean. Default `FALSE` #' @param style path options for the generated lines. See \url{https://web.archive.org/web/20220702182250/https://leafletjs.com/reference-1.3.4.html#path-option} #' @param layerId the layer id #' @param group the name of the group this layer belongs to. diff --git a/R/plugin-minimap.R b/R/plugin-minimap.R index f59c3d4b9..d89b645e8 100644 --- a/R/plugin-minimap.R +++ b/R/plugin-minimap.R @@ -13,13 +13,13 @@ leafletMiniMapDependencies <- function() { ) } -#' Add a minimap to the Map -#' \url{https://github.com/Norkart/Leaflet-MiniMap} +#' Add a minimap to the map #' +#' @seealso \url{https://github.com/Norkart/Leaflet-MiniMap} #' @param map a map widget object #' @param position The standard Leaflet.Control position parameter, #' used like all the other controls. -#' Defaults to "bottomright". +#' Defaults to `"bottomright"`. #' @param width The width of the minimap in pixels. Defaults to 150. #' @param height The height of the minimap in pixels. Defaults to 150. #' @param collapsedWidth The width of the toggle marker and the minimap @@ -39,7 +39,7 @@ leafletMiniMapDependencies <- function() { #' @param zoomAnimation Sets whether the minimap should have an animated zoom. #' (Will cause it to lag a bit after the movement of the main map.) #' Defaults to false. -#' @param toggleDisplay Sets whether the minimap should have a button to minimise it. +#' @param toggleDisplay Sets whether the minimap should have a button to minimize it. #' Defaults to false. #' @param autoToggleDisplay Sets whether the minimap should hide automatically, #' if the parent map bounds does not fit within the minimap bounds. diff --git a/R/plugin-simplegraticule.R b/R/plugin-simplegraticule.R index 319c88934..0e1b77887 100644 --- a/R/plugin-simplegraticule.R +++ b/R/plugin-simplegraticule.R @@ -12,15 +12,14 @@ leafletSimpleGraticuleDependencies <- function() { } #' Add a simple Graticule on the map -#' see \url{https://github.com/ablakey/Leaflet.SimpleGraticule} #' +#' @seealso \url{https://github.com/ablakey/Leaflet.SimpleGraticule} #' @param map a map widget object #' @param interval The spacing in map units between horizontal and vertical lines. #' @param showOriginLabel true Whether or not to show '(0,0)' at the origin. -#' @param redraw on which map event to redraw the graticule. On move is default but moveend can be smoother. +#' @param redraw on which map event to redraw the graticule. On move is default but `"moveend"` can be smoother. #' @param hidden hide on start #' @param zoomIntervals use different intervals in different zoom levels. If not specified, all zoom levels use value in interval option. - #' @param layerId the layer id #' @param group the name of the group this layer belongs to. #' @examples diff --git a/R/utils.R b/R/utils.R index 438d9f036..390580e32 100644 --- a/R/utils.R +++ b/R/utils.R @@ -34,9 +34,11 @@ dispatch <- function(map, stop("Invalid map parameter") } -#' remove NULL elements from a list -#' @param x A list whose NULL elements will be filtered +#' Remove NULL elements from a list +#' @param x A list. #' @export +#' @returns A list with `NULL` elements filtered out. +#' @keywords internal filterNULL <- function(x) { if (length(x) == 0 || !is.list(x)) return(x) x[!unlist(lapply(x, is.null))] diff --git a/inst/examples/awesomeMarkers.R b/inst/examples/awesomeMarkers.R index 8749f8fa7..b7000a160 100644 --- a/inst/examples/awesomeMarkers.R +++ b/inst/examples/awesomeMarkers.R @@ -33,7 +33,7 @@ leaflet() %>% addTiles() %>% addAwesomeMarkers( lng = -118.456554, lat = 34.078039, label = "This is a static label", - labelOptions = labelOptions(noHide = T), + labelOptions = labelOptions(noHide = TRUE), icon = icon.fa) @@ -75,5 +75,5 @@ popIcons <- awesomeIconList( leaflet(cities) %>% addProviderTiles(providers$CartoDB.DarkMatter) %>% addAwesomeMarkers(lng = ~Long, lat = ~Lat, label = ~City, - labelOptions = rep(labelOptions(noHide = T), nrow(cities)), + labelOptions = rep(labelOptions(noHide = TRUE), nrow(cities)), icon = ~popIcons[PopCat] ) diff --git a/inst/examples/labels.R b/inst/examples/labels.R index 985394c73..3b93e5095 100644 --- a/inst/examples/labels.R +++ b/inst/examples/labels.R @@ -12,7 +12,7 @@ leaflet() %>% addTiles() %>% addMarkers( lng = -118.456554, lat = 34.078039, label = "This is a static label", - labelOptions = labelOptions(noHide = T)) + labelOptions = labelOptions(noHide = TRUE)) #'

# Circle Marker + Label in all 4 directions. @@ -24,23 +24,23 @@ leaflet() %>% addTiles() %>% addCircleMarkers( lng = -118.45990, lat = 34.078079, radius = 5, label = "On the Right", - labelOptions = labelOptions(noHide = T, direction = "right") + labelOptions = labelOptions(noHide = TRUE, direction = "right") ) %>% addCircleMarkers( lng = -118.45280, lat = 34.078079, radius = 5, label = "On the left", - labelOptions = labelOptions(noHide = T, direction = "left") + labelOptions = labelOptions(noHide = TRUE, direction = "left") ) %>% addCircleMarkers( lng = -118.456554, lat = 34.079979, radius = 5, label = "On the Top", - labelOptions = labelOptions(noHide = T, direction = "top", + labelOptions = labelOptions(noHide = TRUE, direction = "top", offset = c(0, -15)) ) %>% addCircleMarkers( lng = -118.456554, lat = 34.076279, radius = 5, label = "On the Bottom", - labelOptions = labelOptions(noHide = T, direction = "bottom", + labelOptions = labelOptions(noHide = TRUE, direction = "bottom", offset = c(0, 15))) #'

@@ -50,19 +50,19 @@ leaflet() %>% addTiles() %>% setView(-118.456554, 34.09, 13) %>% addMarkers( lng = -118.456554, lat = 34.07, label = "Default Label", - labelOptions = labelOptions(noHide = T)) %>% + labelOptions = labelOptions(noHide = TRUE)) %>% addMarkers( lng = -118.456554, lat = 34.085, label = "Label w/o surrounding box", - labelOptions = labelOptions(noHide = T, textOnly = TRUE)) %>% + labelOptions = labelOptions(noHide = TRUE, textOnly = TRUE)) %>% addMarkers( lng = -118.456554, lat = 34.095, label = "label w/ textsize 15px", - labelOptions = labelOptions(noHide = T, textsize = "15px")) %>% + labelOptions = labelOptions(noHide = TRUE, textsize = "15px")) %>% addMarkers( lng = -118.456554, lat = 34.11, label = "Label w/ custom CSS style", - labelOptions = labelOptions(noHide = T, textOnly = FALSE, + labelOptions = labelOptions(noHide = TRUE, textOnly = FALSE, style = list( "color" = "red", "font-family" = "serif", @@ -126,7 +126,7 @@ leaflet(cities) %>% addTiles() %>% addCircleMarkers(lng = ~Long, lat = ~Lat, label = ~City, labelOptions = lapply(1:nrow(cities), function(x) { - labelOptions(opacity = 1, noHide = T, + labelOptions(opacity = 1, noHide = TRUE, direction = "auto", offset = c(20, -15)) })) #'

@@ -139,7 +139,7 @@ leaflet(cities) %>% addTiles() %>% function(x, y) { HTML(sprintf("%s: %s", htmlEscape(x), htmlEscape(y))) }, - cities$City, cities$Pop, SIMPLIFY = F), + cities$City, cities$Pop, SIMPLIFY = FALSE), labelOptions = lapply(1:nrow(cities), function(x) { labelOptions(direction = "auto") })) diff --git a/inst/examples/marker-clustering.R b/inst/examples/marker-clustering.R index f33e5a363..9c88fad57 100644 --- a/inst/examples/marker-clustering.R +++ b/inst/examples/marker-clustering.R @@ -24,7 +24,7 @@ l %>% lng = ~long, lat = ~lat, label = ~as.character(mag), clusterOptions = markerClusterOptions(), - labelOptions = labelOptions(noHide = T, + labelOptions = labelOptions(noHide = TRUE, direction = "auto")) #'

#' Clustering + Layers @@ -39,8 +39,8 @@ names(quakes.df) %>% label = ~as.character(mag), popup = ~as.character(mag), group = df, - clusterOptions = markerClusterOptions(removeOutsideVisibleBounds = F), - labelOptions = labelOptions(noHide = T, + clusterOptions = markerClusterOptions(removeOutsideVisibleBounds = FALSE), + labelOptions = labelOptions(noHide = TRUE, direction = "auto")) }) diff --git a/inst/examples/minimap.R b/inst/examples/minimap.R index 1cc88f7f7..65e290a40 100644 --- a/inst/examples/minimap.R +++ b/inst/examples/minimap.R @@ -10,7 +10,7 @@ l %>% addTiles() %>% addMiniMap() l %>% addProviderTiles(providers$Esri.WorldStreetMap) %>% addMiniMap( tiles = providers$Esri.WorldStreetMap, - toggleDisplay = T) + toggleDisplay = TRUE) #'
#' Slightly advanced use case @@ -31,7 +31,7 @@ m %>% ) %>% addMiniMap( tiles = esri[[1]], - toggleDisplay = T) %>% + toggleDisplay = TRUE) %>% htmlwidgets::onRender(" function(el, x) { var myMap = this; @@ -103,7 +103,7 @@ m %>% options = layersControlOptions(collapsed = FALSE) ) %>% addMiniMap(tiles = esri[[1]], - toggleDisplay = T) %>% + toggleDisplay = TRUE) %>% htmlwidgets::onRender(" function(el, t) { var myMap = this; diff --git a/inst/examples/simpleGraticule.R b/inst/examples/simpleGraticule.R index 6f1019d37..30dc257a3 100644 --- a/inst/examples/simpleGraticule.R +++ b/inst/examples/simpleGraticule.R @@ -7,13 +7,13 @@ l %>% addSimpleGraticule() #'
#' Custom Params -l %>% addSimpleGraticule(interval = 40, showOriginLabel = F) +l %>% addSimpleGraticule(interval = 40, showOriginLabel = FALSE) #'
#' Custom Resolution + Custom Date and on a toggleable Layer l %>% addSimpleGraticule(interval = 40, - showOriginLabel = F, + showOriginLabel = FALSE, group = "graticule") %>% addLayersControl( overlayGroups = c("graticule"), diff --git a/man/addGraticule.Rd b/man/addGraticule.Rd index 50d7e6338..b9167d032 100644 --- a/man/addGraticule.Rd +++ b/man/addGraticule.Rd @@ -2,8 +2,7 @@ % Please edit documentation in R/plugin-graticule.R \name{addGraticule} \alias{addGraticule} -\title{Add a Graticule on the map -see \url{https://github.com/turban/Leaflet.Graticule}} +\title{Add a Graticule on the map} \usage{ addGraticule( map, @@ -20,7 +19,7 @@ addGraticule( \item{interval}{The spacing in map units between horizontal and vertical lines.} -\item{sphere}{boolean. Default FALSE} +\item{sphere}{boolean. Default `FALSE`} \item{style}{path options for the generated lines. See \url{https://web.archive.org/web/20220702182250/https://leafletjs.com/reference-1.3.4.html#path-option}} @@ -32,7 +31,6 @@ addGraticule( } \description{ Add a Graticule on the map -see \url{https://github.com/turban/Leaflet.Graticule} } \examples{ leaf <- leaflet() \%>\% @@ -41,3 +39,6 @@ leaf <- leaflet() \%>\% leaf } +\seealso{ +\url{https://github.com/turban/Leaflet.Graticule} +} diff --git a/man/addMiniMap.Rd b/man/addMiniMap.Rd index 06b23d9ef..7ab01ec36 100644 --- a/man/addMiniMap.Rd +++ b/man/addMiniMap.Rd @@ -2,8 +2,7 @@ % Please edit documentation in R/plugin-minimap.R \name{addMiniMap} \alias{addMiniMap} -\title{Add a minimap to the Map -\url{https://github.com/Norkart/Leaflet-MiniMap}} +\title{Add a minimap to the map} \usage{ addMiniMap( map, @@ -31,8 +30,8 @@ addMiniMap( \item{map}{a map widget object} \item{position}{The standard Leaflet.Control position parameter, - used like all the other controls. -Defaults to "bottomright".} +used like all the other controls. +Defaults to `"bottomright"`.} \item{width}{The width of the minimap in pixels. Defaults to 150.} @@ -61,7 +60,7 @@ You can pass in a LatLng-equivalent object. Defaults to false.} (Will cause it to lag a bit after the movement of the main map.) Defaults to false.} -\item{toggleDisplay}{Sets whether the minimap should have a button to minimise it. +\item{toggleDisplay}{Sets whether the minimap should have a button to minimize it. Defaults to false.} \item{autoToggleDisplay}{Sets whether the minimap should hide automatically, @@ -86,8 +85,7 @@ a Path.Options (\url{https://web.archive.org/web/20220702182250/https://leafletj It does not override the MiniMap default map options but extends them.} } \description{ -Add a minimap to the Map -\url{https://github.com/Norkart/Leaflet-MiniMap} +Add a minimap to the map } \examples{ leaf <- leaflet() \%>\% @@ -97,5 +95,7 @@ leaf } \seealso{ +\url{https://github.com/Norkart/Leaflet-MiniMap} + \code{\link{providers}} } diff --git a/man/addSimpleGraticule.Rd b/man/addSimpleGraticule.Rd index 024444626..f6944b326 100644 --- a/man/addSimpleGraticule.Rd +++ b/man/addSimpleGraticule.Rd @@ -2,8 +2,7 @@ % Please edit documentation in R/plugin-simplegraticule.R \name{addSimpleGraticule} \alias{addSimpleGraticule} -\title{Add a simple Graticule on the map -see \url{https://github.com/ablakey/Leaflet.SimpleGraticule}} +\title{Add a simple Graticule on the map} \usage{ addSimpleGraticule( map, @@ -23,7 +22,7 @@ addSimpleGraticule( \item{showOriginLabel}{true Whether or not to show '(0,0)' at the origin.} -\item{redraw}{on which map event to redraw the graticule. On move is default but moveend can be smoother.} +\item{redraw}{on which map event to redraw the graticule. On move is default but `"moveend"` can be smoother.} \item{hidden}{hide on start} @@ -35,7 +34,6 @@ addSimpleGraticule( } \description{ Add a simple Graticule on the map -see \url{https://github.com/ablakey/Leaflet.SimpleGraticule} } \examples{ \donttest{leaflet() \%>\% @@ -43,3 +41,6 @@ see \url{https://github.com/ablakey/Leaflet.SimpleGraticule} addSimpleGraticule()} } +\seealso{ +\url{https://github.com/ablakey/Leaflet.SimpleGraticule} +} diff --git a/man/awesomeIcons.Rd b/man/awesomeIcons.Rd index 7c314f5e0..4b8290690 100644 --- a/man/awesomeIcons.Rd +++ b/man/awesomeIcons.Rd @@ -2,8 +2,7 @@ % Please edit documentation in R/plugin-awesomeMarkers.R \name{awesomeIcons} \alias{awesomeIcons} -\title{Create a list of awesome icon data see -\url{https://github.com/lennardv2/Leaflet.awesome-markers}} +\title{Create a list of awesome icon data} \usage{ awesomeIcons( icon = "home", @@ -52,6 +51,9 @@ A list of awesome-icon data that can be passed to the \code{icon} \description{ An icon can be represented as a list of the form \code{list(icon, library, ...)}. This function is vectorized over its arguments to create a list of -icon data. Shorter argument values will be re-cycled. \code{NULL} values for +icon data. Shorter argument values will be recycled. \code{NULL} values for these arguments will be ignored. } +\seealso{ +\url{https://github.com/lennardv2/Leaflet.awesome-markers} +} diff --git a/man/derivePoints.Rd b/man/derivePoints.Rd index 0b6aa9152..32f0f3d2b 100644 --- a/man/derivePoints.Rd +++ b/man/derivePoints.Rd @@ -2,9 +2,8 @@ % Please edit documentation in R/normalize.R \name{derivePoints} \alias{derivePoints} -\title{Given a data object and lng/lat arguments (which may be NULL [meaning infer -from data], formula [which should be evaluated with respect to the data], or -vector data [which should be used as-is]) return a lng/lat data frame.} +\alias{derivePolygons} +\title{Normalize data to a data frame or Spatial object.} \usage{ derivePoints( data, @@ -14,13 +13,20 @@ derivePoints( missingLat = missing(lat), funcName = "f" ) + +derivePolygons( + data, + lng = NULL, + lat = NULL, + missingLng = missing(lng), + missingLat = missing(lat), + funcName = "f" +) } \arguments{ \item{data}{map data} -\item{lng}{longitude} - -\item{lat}{latitude} +\item{lng, lat}{longitude and latitude} \item{missingLng}{whether lng is missing} @@ -28,8 +34,13 @@ derivePoints( \item{funcName}{Name of calling function (for logging)} } +\value{ +* `derivePoints()` returns a lng/lat data frame. +* `derivePolygons()` returns a list with bbox attributes. +} \description{ -Given a data object and lng/lat arguments (which may be NULL [meaning infer -from data], formula [which should be evaluated with respect to the data], or +Given a data object and lng/lat arguments (which may be `NULL`) +[meaning infer from data], formula [which should be evaluated with respect to the data], or vector data [which should be used as-is]) return a lng/lat data frame. } +\keyword{internal} diff --git a/man/derivePolygons.Rd b/man/derivePolygons.Rd deleted file mode 100644 index a1cfbbd70..000000000 --- a/man/derivePolygons.Rd +++ /dev/null @@ -1,35 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/normalize.R -\name{derivePolygons} -\alias{derivePolygons} -\title{Given a data object and lng/lat arguments (which may be NULL [meaning infer -from data], formula [which should be evaluated with respect to the data], or -vector data [which should be used as-is]) return a spatial object} -\usage{ -derivePolygons( - data, - lng = NULL, - lat = NULL, - missingLng = missing(lng), - missingLat = missing(lat), - funcName = "f" -) -} -\arguments{ -\item{data}{map data} - -\item{lng}{longitude} - -\item{lat}{latitude} - -\item{missingLng}{whether lng is missing} - -\item{missingLat}{whether lat is missing} - -\item{funcName}{Name of calling function (for logging)} -} -\description{ -Given a data object and lng/lat arguments (which may be NULL [meaning infer -from data], formula [which should be evaluated with respect to the data], or -vector data [which should be used as-is]) return a spatial object -} diff --git a/man/evalFormula.Rd b/man/evalFormula.Rd index 4636fab64..830b3fd80 100644 --- a/man/evalFormula.Rd +++ b/man/evalFormula.Rd @@ -2,8 +2,7 @@ % Please edit documentation in R/layers.R \name{evalFormula} \alias{evalFormula} -\title{Evaluate list members that are formulae, using the map data as the environment -(if provided, otherwise the formula environment)} +\title{Evaluate list members that are formulae, using the map data as the environment} \usage{ evalFormula(list, data) } @@ -13,6 +12,6 @@ evalFormula(list, data) \item{data}{map data} } \description{ -Evaluate list members that are formulae, using the map data as the environment -(if provided, otherwise the formula environment) +Evaluates if provided. Otherwise, the formula environment is evaluated. } +\keyword{internal} diff --git a/man/expandLimitsBbox.Rd b/man/expandLimitsBbox.Rd index 05b2b0cdb..17785edc7 100644 --- a/man/expandLimitsBbox.Rd +++ b/man/expandLimitsBbox.Rd @@ -2,8 +2,7 @@ % Please edit documentation in R/layers.R \name{expandLimitsBbox} \alias{expandLimitsBbox} -\title{Same as expandLimits, but takes a polygon (that presumably has a bbox attr) -rather than lat/lng.} +\title{Notifies the map of polygons of interest on the map} \usage{ expandLimitsBbox(map, poly) } @@ -13,6 +12,6 @@ expandLimitsBbox(map, poly) \item{poly}{A spatial object representing a polygon.} } \description{ -Same as expandLimits, but takes a polygon (that presumably has a bbox attr) +Same as `expandLimits()`, but takes a polygon (that presumably has a bbox attr) rather than lat/lng. } diff --git a/man/filterNULL.Rd b/man/filterNULL.Rd index 1204a08be..a318cb83c 100644 --- a/man/filterNULL.Rd +++ b/man/filterNULL.Rd @@ -2,13 +2,17 @@ % Please edit documentation in R/utils.R \name{filterNULL} \alias{filterNULL} -\title{remove NULL elements from a list} +\title{Remove NULL elements from a list} \usage{ filterNULL(x) } \arguments{ -\item{x}{A list whose NULL elements will be filtered} +\item{x}{A list.} +} +\value{ +A list with `NULL` elements filtered out. } \description{ -remove NULL elements from a list +Remove NULL elements from a list } +\keyword{internal} diff --git a/man/getMapData.Rd b/man/getMapData.Rd index bb2894fa3..0893ffdf9 100644 --- a/man/getMapData.Rd +++ b/man/getMapData.Rd @@ -2,13 +2,16 @@ % Please edit documentation in R/leaflet.R \name{getMapData} \alias{getMapData} -\title{returns the map's data} +\title{Extract the map's data} \usage{ getMapData(map) } \arguments{ \item{map}{the map} } +\value{ +The map's data +} \description{ -returns the map's data +Extract the map's data } diff --git a/man/leaflet-imports.Rd b/man/leaflet-imports.Rd deleted file mode 100644 index bb27279f4..000000000 --- a/man/leaflet-imports.Rd +++ /dev/null @@ -1,11 +0,0 @@ -\name{leaflet-imports} -\alias{JS} -\alias{\%>\%} -\docType{import} -\title{Objects imported from other packages} -\description{ -These objects are imported from other packages. Follow the links to their documentation. -\describe{ - \item{htmlwidgets}{\code{\link[htmlwidgets:JS]{JS}}} - \item{magrittr}{\code{\link[magrittr:\%>\%]{\%>\%}}} -}} diff --git a/man/map-options.Rd b/man/map-options.Rd index 143edbcaa..3d0faf412 100644 --- a/man/map-options.Rd +++ b/man/map-options.Rd @@ -172,7 +172,7 @@ to style spider legs. By default, they are \item{freezeAtZoom}{Allows you to freeze cluster expansion to a zoom level. Can be a zoom level e.g. 10, 12 or "max" or "maxKeepSpiderify". -See .} +See \url{https://github.com/ghybs/Leaflet.MarkerCluster.Freezable#api-reference}.} \item{lineCap}{a string that defines \href{https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-linecap}{shape diff --git a/man/reexports.Rd b/man/reexports.Rd new file mode 100644 index 000000000..66cb34314 --- /dev/null +++ b/man/reexports.Rd @@ -0,0 +1,19 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/leaflet-package.R +\docType{import} +\name{reexports} +\alias{reexports} +\alias{\%>\%} +\alias{JS} +\title{Objects exported from other packages} +\keyword{internal} +\description{ +These objects are imported from other packages. Follow the links +below to see their documentation. + +\describe{ + \item{htmlwidgets}{\code{\link[htmlwidgets]{JS}}} + + \item{magrittr}{\code{\link[magrittr:pipe]{\%>\%}}} +}} + diff --git a/pkgdown/_pkgdown.yml b/pkgdown/_pkgdown.yml index 1a35a09b4..506577dd6 100644 --- a/pkgdown/_pkgdown.yml +++ b/pkgdown/_pkgdown.yml @@ -9,6 +9,50 @@ template: navbar-background: "#f8f8f8" trailing_slash_redirect: true +footer: + structure: + left: [developed_by, copyright] + components: + copyright: > + The Leaflet JavaScript library is © 2010–2023 [Vladimir Agafonkin](http://agafonkin.com/en), 2010–2011 [CloudMade](http://cloudmade.com/). + Maps © [OpenStreetMap](https://openstreetmap.org/copyright) contributors unless otherwise noted. + +intro: +- title: Get started + contents: + - articles/leaflet + +articles: +- title: Get started + navbar: ~ + contents: + - articles/widget + - articles/choropleths + - articles/colors + +- title: Customize + navbar: Customize + contents: + - articles/popups + - articles/showhide + - articles/markers + - articles/legends + - articles/shapes + - articles/basemaps +- title: Spatial data + navbar: Spatial data + contents: + - articles/json + - articles/raster + - articles/projections + +- title: Other + contents: + - articles/shiny + - articles/morefeatures + - articles/extending + - articles/leaflet + redirects: - ["basemaps.html", "articles/basemaps.html"] - ["choropleths.html", "articles/choropleths.html"] diff --git a/pkgdown/assets/nc/oisst-sst.nc b/pkgdown/assets/nc/oisst-sst.nc new file mode 100644 index 000000000..9e840b2c3 Binary files /dev/null and b/pkgdown/assets/nc/oisst-sst.nc differ diff --git a/scripts/scratch.Rmd b/scripts/scratch.Rmd index d3951ead1..72958d6cc 100644 --- a/scripts/scratch.Rmd +++ b/scripts/scratch.Rmd @@ -12,7 +12,7 @@ The UI elements markers and popups are supported via `addMarkers()` and `addPopu ```{r} leaflet() %>% addTiles() %>% addMarkers(174.7690922, -36.8523071, icon = icons( - iconUrl = 'http://cran.rstudio.com/Rlogo.jpg', + iconUrl = 'https://cran.rstudio.com/Rlogo.jpg', iconWidth = 40, iconHeight = 40 )) %>% addPopups(174.7690922, -36.8523071, 'R was born here!') @@ -22,7 +22,7 @@ leaflet() %>% addTiles() %>% Currently tile layers are supported via `addTiles()`. By default, the OpenStreetMap tiles are used, and you can certainly use other tiles of your choice. -A live demo of many tile sets is available [here](http://leaflet-extras.github.io/leaflet-providers/preview/index.html). Note that some tile set providers require you to register. See the [project page](https://github.com/leaflet-extras/leaflet-providers) for more information. +A live demo of many tile sets is available [here](https://leaflet-extras.github.io/leaflet-providers/preview/). Note that some tile set providers require you to register. See the [project page](https://github.com/leaflet-extras/leaflet-providers) for more information. ```{r} leaflet() %>% @@ -68,7 +68,7 @@ m %>% addPolygons( # Other Layers -[GeoJSON](http://geojson.org) is a JSON format for encoding geographic data structures such as points, lines, and polygons. The function `addGeoJSON()` allows us to add a GeoJSON layer to the map, and the layer data is normally represented as an R list. For example, the GeoJSON data +[GeoJSON](https://geojson.org/) is a JSON format for encoding geographic data structures such as points, lines, and polygons. The function `addGeoJSON()` allows us to add a GeoJSON layer to the map, and the layer data is normally represented as an R list. For example, the GeoJSON data ```javascript var MPoint = { diff --git a/vignettes/articles/basemaps.Rmd b/vignettes/articles/basemaps.Rmd index 924f77556..28ba7fadc 100644 --- a/vignettes/articles/basemaps.Rmd +++ b/vignettes/articles/basemaps.Rmd @@ -9,11 +9,10 @@ knitr::opts_chunk$set( ) ``` -## Using Basemaps Leaflet supports basemaps using [map tiles](https://www.mapbox.com/guides/how-web-maps-work/), popularized by Google Maps and now used by nearly all interactive web maps. -### Default (OpenStreetMap) Tiles +# Default (OpenStreetMap) Tiles The easiest way to add tiles is by calling `addTiles()` with no arguments; by default, [OpenStreetMap](https://www.openstreetmap.org/) tiles are used. @@ -23,7 +22,7 @@ m <- leaflet() %>% setView(lng = -71.0589, lat = 42.3601, zoom = 12) m %>% addTiles() ``` -### Third-Party Tiles +# Third-Party Tiles Alternatively, many popular free third-party basemaps can be added using the `addProviderTiles()` function, which is implemented using the [leaflet-providers plugin](https://github.com/leaflet-extras/leaflet-providers). See [here](http://leaflet-extras.github.io/leaflet-providers/preview/index.html) for the complete set. @@ -37,13 +36,13 @@ m %>% addProviderTiles(providers$Esri.NatGeoWorldMap) Note that some tile set providers require you to register; see the [project page](https://github.com/leaflet-extras/leaflet-providers) for more information. You can pass access tokens/keys, and other options, to the tile provider by populating the `options` argument with the `providerTileOptions()` function. -### Custom Tile URL Template +# Custom Tile URL Template If you happen to have a custom map tile URL template to use, you can provide it as an argument to `addTiles()`. -### WMS Tiles +# WMS Tiles -You can use `addWMSTiles()` to add WMS (Web Map Service) tiles. The map below shows the Base Reflectivity (a measure of the intensity of precipitation occurring) using the WMS from the [Iowa Environmental Mesonet ](http://mesonet.agron.iastate.edu): +You can use `addWMSTiles()` to add WMS (Web Map Service) tiles. The map below shows the Base Reflectivity (a measure of the intensity of precipitation occurring) using the WMS from the [Iowa Environmental Mesonet ](https://mesonet.agron.iastate.edu/): ```{r fig.height=2.5} leaflet() %>% addTiles() %>% setView(-93.65, 42.0285, zoom = 4) %>% @@ -55,7 +54,7 @@ leaflet() %>% addTiles() %>% setView(-93.65, 42.0285, zoom = 4) %>% ) ``` -### Combining Tile Layers +# Combining Tile Layers You aren't restricted to using a single basemap on a map; you can stack them by adding multiple tile layers. This generally only makes sense if the front tiles consist of semi transparent tiles, or have an adjusted opacity via the `options` argument. diff --git a/vignettes/articles/choropleths.Rmd b/vignettes/articles/choropleths.Rmd index aecf0e43c..236705a59 100644 --- a/vignettes/articles/choropleths.Rmd +++ b/vignettes/articles/choropleths.Rmd @@ -13,13 +13,13 @@ Making choropleths with leaflet is easy. In this example, we'll duplicate the [s The final result will look like this (scroll to the end to see the completed code): -```{r, include = FALSE} +```{r, include = FALSE, message = FALSE} library(leaflet) library(magrittr) ``` -```{r fig.height = 4.75, echo = FALSE} -# From http://leafletjs.com/examples/choropleth/us-states.js +```{r fig.height = 4.75, echo = FALSE, message = FALSE} +# From https://leafletjs.com/examples/choropleth/us-states.js states <- geojsonio::geojson_read("https://rstudio.github.io/leaflet/json/us-states.geojson", what = "sp") bins <- c(0, 10, 20, 50, 100, 200, 500, 1000, Inf) @@ -63,6 +63,7 @@ We'll start by loading the data from JSON. While the Leaflet.js example loads th In this case, we'll use the `geojsonio` package to load the data into `sp` objects, which will let us easily manipulate the geographic features, and their properties, in R. + ```{r} states <- geojsonio::geojson_read("https://rstudio.github.io/leaflet/json/us-states.geojson", what = "sp") class(states) @@ -73,7 +74,7 @@ As you can see, we now have a `SpatialPolygonsDataFrame` with `name` (state name ### Basic states map -Next, let's make a basic map with just the outline of the states. For our basemap, we'll use the same `"mapbox.light"` MapBox style that the example does; if you don't have a MapBox account, you can just use `addTiles()` in place of the `addProviderTiles` call, or choose a free provider. +Next, let's make a basic map with just the outline of the states. For our basemap, we'll use the same `"mapbox.light"` MapBox style that the example does; if you don't have a MapBox account, you can just use `addTiles()` in place of the `addProviderTiles()` call, or choose a free provider. ```{r} m <- leaflet(states) %>% @@ -83,9 +84,9 @@ m <- leaflet(states) %>% accessToken = Sys.getenv('MAPBOX_ACCESS_TOKEN'))) ``` -We've saved the basic basemap as a separate variable `m` so we can easily iterate on the `addPolygons` call as we work through the rest of the tutorial. +We've saved the basic basemap as a separate variable `m` so we can easily iterate on the `addPolygons()` call as we work through the rest of the tutorial. -To add uniform polygons with default styling, just call `addPolygons` with no additional arguments. +To add uniform polygons with default styling, just call `addPolygons()` with no additional arguments. ```{r} m %>% addPolygons() @@ -93,13 +94,13 @@ m %>% addPolygons() ### Adding some color -Now, let's color the states according to their population density. You have [various options](../colors.html) for mapping data to colors; for this example we'll match the Leaflet.js tutorial by mapping a specific set of bins into RColorBrewer colors. +Now, let's color the states according to their population density. You have [various options](https://rstudio.github.io/leaflet/articles/colors.html) for mapping data to colors; for this example we'll match the Leaflet.js tutorial by mapping a specific set of bins into RColorBrewer colors. First, we'll define the bins. This is a numeric vector that defines the boundaries between intervals (`(0,10]`, `(10,20]`, and so on). -Then, we'll call `colorBin` to generate a palette function that maps the RColorBrewer `"YlOrRd"` colors to our bins. +Then, we'll call `colorBin()` to generate a palette function that maps the RColorBrewer `"YlOrRd"` colors to our bins. -Finally, we'll modify `addPolygons` to use the palette function and the density values to generate a vector of colors for `fillColor`, and also add some other static style properties. +Finally, we'll modify `addPolygons()` to use the palette function and the density values to generate a vector of colors for `fillColor`, and also add some other static style properties. ```{r} bins <- c(0, 10, 20, 50, 100, 200, 500, 1000, Inf) @@ -116,7 +117,7 @@ m %>% addPolygons( ### Adding interaction -The next thing we'll want is to make the polygons highlight as the mouse passes over them. The `addPolygon` function has a `highlight` argument that makes this simple. +The next thing we'll want is to make the polygons highlight as the mouse passes over them. The `addPolygon()` function has a `highlight` argument that makes this simple. ```{r} m %>% addPolygons( @@ -175,7 +176,7 @@ This is the final version of our polygon layer, so let's save the result back to ### Legend -As our final step, let's add a legend. Because we chose to color our map using `colorBin`, the `addLegend` function makes it particularly easy to add a legend with the correct colors and intervals. +As our final step, let's add a legend. Because we chose to color our map using `colorBin()`, the `addLegend()` function makes it particularly easy to add a legend with the correct colors and intervals. ```{r} m %>% addLegend(pal = pal, values = ~density, opacity = 0.7, title = NULL, @@ -185,7 +186,7 @@ m %>% addLegend(pal = pal, values = ~density, opacity = 0.7, title = NULL, ### Complete code ```{r results = 'hide'} -# From http://leafletjs.com/examples/choropleth/us-states.js +# From https://leafletjs.com/examples/choropleth/us-states.js states <- geojsonio::geojson_read("https://rstudio.github.io/leaflet/json/us-states.geojson", what = "sp") bins <- c(0, 10, 20, 50, 100, 200, 500, 1000, Inf) diff --git a/vignettes/articles/colors.Rmd b/vignettes/articles/colors.Rmd index f1990d89c..654a0f08a 100644 --- a/vignettes/articles/colors.Rmd +++ b/vignettes/articles/colors.Rmd @@ -1,5 +1,5 @@ --- -title: "Add color to a leaflet" +title: "Colors" --- ```{r, include = FALSE} @@ -9,11 +9,9 @@ knitr::opts_chunk$set( ) ``` -## Colors - An important part of spatial visualization is mapping variables to colors. While R has no shortage of built-in functionality to map values to colors, we found that there was enough friction in the process to warrant introducing some wrapper functions that do a lot of the work for you. -To that end, we've created a family of `color*` convenience functions that can be used to easily generate *palette functions*. Essentially, you call the appropriate color function with 1) the colors you want to use and 2) optionally, the range of inputs (i.e. *domain*) that are expected. The color function returns a palette function that can be passed a vector of input values, and it'll return a vector of colors in `#RRGGBB(AA)` format. +To that end, we've created a family of `color*()` convenience functions that can be used to easily generate *palette functions*. Essentially, you call the appropriate color function with 1) the colors you want to use and 2) optionally, the range of inputs (i.e. *domain*) that are expected. The color function returns a palette function that can be passed a vector of input values, and it'll return a vector of colors in `#RRGGBB(AA)` format. ```{r, include = FALSE} library(leaflet) @@ -28,9 +26,9 @@ pal <- colorNumeric(c("red", "green", "blue"), 1:10) pal(c(1,6,9)) ``` -There are currently three color functions for dealing with continuous input: `colorNumeric`, `colorBin`, and `colorQuantile`; and one for categorical input, `colorFactor`. +There are currently three color functions for dealing with continuous input: `colorNumeric()`, `colorBin()`, and `colorQuantile()`; and one for categorical input, `colorFactor()`. -### Common parameters +# Common parameters The four color functions all have two required arguments, `palette` and `domain`. @@ -44,7 +42,7 @@ The `palette` argument specifies the colors to map the data to. This argument ca The `domain` argument tells the color function the range of input values. You can pass `NULL` here to create a palette function that doesn't have a preset range; the range will be inferred from the data each time you invoke the palette function. If you use a palette function multiple times across different data, it's important to provide a non-`NULL` value for `domain` so the scaling between data and colors is consistent. -### Coloring continuous data +## Coloring continuous data ```{r message=FALSE,warning=FALSE,results='hide'} @@ -60,9 +58,9 @@ par(mar = c(5,5,0,0), cex = 0.8) hist(countries$gdp_md_est, breaks = 20, main = "") ``` -#### Continuous input, continuous colors (`colorNumeric`) +### Continuous input, continuous colors (`colorNumeric`) -Let's start by mapping GDP values directly to the `"Blues"` palette from [Color Brewer 2](http://colorbrewer2.org). We'll use the `colorNumeric` function to create a mapping function. The `"Blues"` palette only contains nine colors, but `colorNumeric` interpolates these colors so we get continuous output. +Let's start by mapping GDP values directly to the `"Blues"` palette from [Color Brewer 2](https://colorbrewer2.org/). We'll use `colorNumeric()` to create a mapping function. The `"Blues"` palette only contains nine colors, but `colorNumeric()` interpolates these colors so we get continuous output. ```{r} # Create a continuous palette function @@ -73,7 +71,7 @@ pal <- colorNumeric( The `palette` parameter is the ordered list of colors you will map colors to. In this case we used a Color Brewer palette, but we could've used `c("white", "navy")` or `c("#FFFFFF", "#000080")` for a similar effect. You can also pass more than two colors, for a diverging palette for example. And for maximum flexibility, you can even pass a function that takes a numeric value over the interval [0,1] and returns a color. -The second parameter, `domain`, indicates the set of input values that we are mapping to these colors. For `colorNumeric`, you can provide either a min/max as in this example, or a set of numbers that `colorNumeric` can call `range()` on. +The second parameter, `domain`, indicates the set of input values that we are mapping to these colors. For `colorNumeric()`, you can provide either a min/max as in this example, or a set of numbers that `colorNumeric()` can call `range()` on. The result is `pal`, a function that can accept numeric vectors with values in the range `range(countries$gdp_md_est)` and return colors in `"#RRGGBB"` format. @@ -84,11 +82,11 @@ map %>% color = ~pal(gdp_md_est)) ``` -#### Continuous input, discrete colors (`colorBin` and `colorQuantile`) +### Continuous input, discrete colors (`colorBin` and `colorQuantile`) -`colorBin` maps numeric input data to a fixed number of output colors using binning (slicing the input domain up by value). +`colorBin()` maps numeric input data to a fixed number of output colors using binning (slicing the input domain up by value). -You can specify either the exact breaks to use, or the desired number of bins. Note that in the latter case, if `pretty=TRUE` (the default) you'll end up with nice round breaks but not necessarily the number of bins you wanted. +You can specify either the exact breaks to use, or the desired number of bins. Note that in the latter case, if `pretty = TRUE` (the default) you'll end up with nice round breaks but not necessarily the number of bins you wanted. ```{r} binpal <- colorBin("Blues", countries$gdp_md_est, 6, pretty = FALSE) @@ -98,7 +96,7 @@ map %>% color = ~binpal(gdp_md_est)) ``` -`colorQuantile` maps numeric input data to a fixed number of output colors using quantiles (slicing the input domain into subsets with equal numbers of observations). +`colorQuantile()` maps numeric input data to a fixed number of output colors using quantiles (slicing the input domain into subsets with equal numbers of observations). ```{r} qpal <- colorQuantile("Blues", countries$gdp_md_est, n = 7) @@ -107,9 +105,9 @@ map %>% color = ~qpal(gdp_md_est)) ``` -### Coloring categorical data +## Coloring categorical data -For categorical data, use the `colorFactor` function. If the `palette` contains the same number of elements as there are factor levels, then the mapping will be 1:1; otherwise, the palette will be interpolated to produce the desired number of colors. +For categorical data, use `colorFactor()`. If the `palette` contains the same number of elements as there are factor levels, then the mapping will be 1:1; otherwise, the palette will be interpolated to produce the desired number of colors. You can specify the input domain either by passing a factor or character vector to `domain`, or by providing levels directly using the `levels` parameter (in which case the `domain` will be ignored). diff --git a/vignettes/articles/extending.Rmd b/vignettes/articles/extending.Rmd index 1996189f7..37bff1623 100644 --- a/vignettes/articles/extending.Rmd +++ b/vignettes/articles/extending.Rmd @@ -9,39 +9,39 @@ knitr::opts_chunk$set( ) ``` -## Extending Leaflet package - -The Leaflet Javascript library has a plethora of [plugins](leafletjs.com/plugins) available that extend the functionality of the core package. We have incorporated a chosen few in the R package. It may be desirable to use plugins availble outside of what are supported by this pakage. +The Leaflet JavaScript library has a plethora of [plugins](https://leafletjs.com/plugins) available that extend the functionality of the core package. We have incorporated a chosen few in the R package. It may be desirable to use plugins available outside of what are supported by this package. The way to achieve that is by extending the Leaflet package. By extending we mean writing your own code/package that incorporate your desired leaflet plugins and hook into the leaflet package. +# Functions for extending leaflet + Certain functions have been made available for you to use in your code while extending Leaflet. -#### derivePoints/derivePolygons +## derivePoints/derivePolygons -These functions can be used to extract point or shape (polygon/line/circle/rectangle) data from a `data.frame` or a spatial object from the `sp` package. It tries to auto determine the latitude/longitude colnames if not specified or use user supplied column mappings. +`derivePoints()` and `derivePolygons()` can be used to extract point or shape (polygon/line/circle/rectangle) data from a `data.frame` or a spatial object from the `sp` package. It tries to auto determine the latitude/longitude colnames if not specified or use user supplied column mappings. -#### evalFormula +## evalFormula -`evalFormula` is used to evaluate a formula on a given data and return the results. e.g. `leaflet(some.data.frame) %>% addMarkers(label=~name)` internally uses `evalFormula` to calculate the correct label values from the data using the `~name` formula. +`evalFormula()` is used to evaluate a formula on a given data and return the results. e.g. `leaflet(some.data.frame) %>% addMarkers(label=~name)` internally uses `evalFormula()` to calculate the correct label values from the data using the `~name` formula. -#### expandLimits +## expandLimits -You can call `expandLimits` to make sure that your map's view is just enough to show every point/shape in your data. This way you don't have to determine the exact bounds for your map. +You can call `expandLimits()` to make sure that your map's view is just enough to show every point/shape in your data. This way you don't have to determine the exact bounds for your map. -#### filterNULL +## filterNULL -Often when passing a list from R to Javascript it is desirable to remove any null elements, and that's exactly what `filterNULL` does. +Often when passing a list from R to Javascript it is desirable to remove any null elements, and that's exactly what `filterNULL()` does. -#### getMapData +## getMapData -Accesses the data object passed when calling `leaflet()` funtion. +`getMapData()` accesses the data object passed when calling `leaflet()` funtion. -#### invokeMethod +## invokeMethod -The glue between the R code and Javascript code. Requires a corresponding method on the Javascript side. +`invokeMethod()` is the glue between the R code and JavaScript code. Requires a corresponding method on the Javascript side. -### Example +# Example Here is a small example which shows how you can integrate the Bing.com basemap layer [plugin](https://github.com/shramov/leaflet-plugins) diff --git a/vignettes/articles/json.Rmd b/vignettes/articles/json.Rmd index 21d3f609a..476f0b959 100644 --- a/vignettes/articles/json.Rmd +++ b/vignettes/articles/json.Rmd @@ -3,13 +3,11 @@ title: "Working with GeoJSON & TopoJSON" --- -## Working with GeoJSON & TopoJSON - For working with GeoJSON/TopoJSON data you have two options: either read it into `sp` objects; or use the `addGeoJSON()` and `addTopoJSON()` functions. -### Reading as `sp` +# Reading as `sp` -The first approach is to use either `sf` or `geojsonio` (packages) to read GeoJSON/TopoJSON as `sp` objects. Then, you can use the full functionality of [polygons](shapes.html), [markers](markers.html), [colors](colors.html), [legends](legends.html), etc. +The first approach is to use either `sf` or `geojsonio` (packages) to read GeoJSON/TopoJSON as `sp` objects. Then, you can use the full functionality of [polygons](https://rstudio.github.io/leaflet/articles/shapes.html), [markers](https://rstudio.github.io/leaflet/articles/markers.html), [colors](https://rstudio.github.io/leaflet/articles/colors.html), [legends](https://rstudio.github.io/leaflet/articles/legends.html), etc. ```{r, include = FALSE} library(leaflet) @@ -17,7 +15,7 @@ library(magrittr) ``` ```{r message=FALSE,warning=FALSE} -# From http://eric.clst.org/Stuff/USGeoJSON and +# From https://eric.clst.org/tech/usgeojson/ and # https://en.wikipedia.org/wiki/List_of_United_States_counties_and_county_equivalents nycounties <- sf::read_sf("https://rstudio.github.io/leaflet/json/nycounties.geojson") # Or use the geojsonio equivalent: @@ -34,13 +32,13 @@ leaflet(nycounties) %>% labFormat = labelFormat(transform = function(x) round(10^x))) ``` -This approach is preferred over using `addGeoJSON`/`addTopoJSON`, as it makes it easy to use feature properties in determining map colors, labels, etc., or to modify or add new properties. +This approach is preferred over using `addGeoJSON()`/`addTopoJSON()`, as it makes it easy to use feature properties in determining map colors, labels, etc., or to modify or add new properties. The main downside to this approach is that it only supports feature collections where all features are of the same type, whereas in GeoJSON/TopoJSON it's possible—though uncommon—to have a single feature collection that contains, say, both markers and polygons. -### Working with raw GeoJSON/TopoJSON +# Working with raw GeoJSON/TopoJSON -The `addGeoJSON()` and `addTopoJSON()` functions accept GeoJSON data in either parsed (nested lists) or stringified (single-element character vector) format. +`addGeoJSON()` and `addTopoJSON()` accept GeoJSON data in either parsed (nested lists) or stringified (single-element character vector) format. Note that for larger JSON data, using parsed is significantly slower than using stringified, because parsed data must go through a JSON encoding step. @@ -54,11 +52,11 @@ leaflet() %>% setView(lng = -98.583, lat = 39.833, zoom = 3) %>% addTopoJSON(topoData, weight = 1, color = "#444444", fill = FALSE) ``` -#### Styling raw GeoJSON/TopoJSON +# Styling raw GeoJSON/TopoJSON You can modify the style of GeoJSON/TopoJSON features in a few ways. (Currently only paths and shapes can be styled; marker styling is not supported.) -One way to apply styles to all of the features is to use the arguments directly on the `addGeoJSON`/`addTopoJSON` functions. Another way is to encode styling information directly in the JSON object/string by putting a `style` object directly underneath the top level JSON object. +One way to apply styles to all of the features is to use the arguments directly with `addGeoJSON()`/`addTopoJSON()`. Another way is to encode styling information directly in the JSON object/string by putting a `style` object directly underneath the top level JSON object. You can provide feature-specific styles by annotating each feature's property object with a `style: {...}` object. The feature-specific styles have the highest precedence, then the top-level style object, and finally the style-related arguments passed to the function. diff --git a/vignettes/leaflet.Rmd b/vignettes/articles/leaflet.Rmd similarity index 91% rename from vignettes/leaflet.Rmd rename to vignettes/articles/leaflet.Rmd index 5d28df8bf..e78f1d4ae 100644 --- a/vignettes/leaflet.Rmd +++ b/vignettes/articles/leaflet.Rmd @@ -26,7 +26,7 @@ This R package makes it easy to integrate and control Leaflet maps in R. * Popups * GeoJSON * Create maps right from the R console or RStudio -* Embed maps in [knitr](https://yihui.org/knitr/)/[R Markdown](https://rmarkdown.rstudio.com/) documents and [Shiny](https://shiny.posit.co/) apps +* Embed maps in [knitr](https://yihui.org/knitr/)/[R Markdown](https://rmarkdown.rstudio.com/)/[Quarto](https://quarto.org) documents, and [Shiny](https://shiny.posit.co/) apps * Easily render spatial objects from the `sp` or `sf` packages, or data frames with latitude/longitude columns * Use map bounds and mouse events to drive Shiny logic * Display maps in non spherical mercator projections @@ -64,7 +64,7 @@ m <- leaflet() %>% m # Print the map ``` -In case you're not familiar with the [magrittr](https://github.com/tidyverse/magrittr) pipe operator (`%>%`), here is the equivalent without using pipes: +In case you're not familiar with the pipe ([magrittr](https://github.com/tidyverse/magrittr) or base) operator (`%>%` / `|>`), here is the equivalent without using pipes: ```{r eval=FALSE} m <- leaflet() diff --git a/vignettes/articles/markers.Rmd b/vignettes/articles/markers.Rmd index 768538b68..dabe80d44 100644 --- a/vignettes/articles/markers.Rmd +++ b/vignettes/articles/markers.Rmd @@ -1,5 +1,5 @@ --- -title: "Markers" +title: "Add markers to leaflet" --- ```{r, include = FALSE} @@ -15,21 +15,21 @@ library(leaflet) Use markers to call out points on the map. Marker locations are expressed in latitude/longitude coordinates, and can either appear as icons or as circles. -### Data sources +# Data sources Point data for markers can come from a variety of sources: - `SpatialPoints` or `SpatialPointsDataFrame` objects (from the `sp` package) - `POINT`, `sfc_POINT`, and `sf` objects (from the `sf` package); only `X` and `Y` dimensions will be considered - Two-column numeric matrices (first column is longitude, second is latitude) -- Data frame with latitude and logitude columns. You can explicitly tell the marker function which columns contain the coordinate data (e.g. `addMarkers(lng = ~Longitude, lat = ~Latitude)`), or let the function look for columns named `lat`/`latitude` and `lon`/`lng`/`long`/`longitude` (case insensitive). +- Data frame with latitude and longitude columns. You can explicitly tell the marker function which columns contain the coordinate data (e.g. `addMarkers(lng = ~Longitude, lat = ~Latitude)`), or let the function look for columns named `lat`/`latitude` and `lon`/`lng`/`long`/`longitude` (case insensitive). - Simply provide numeric vectors as `lng` and `lat` arguments Note that `MULTIPOINT` objects from `sf` are not supported at this time. -### Icon Markers +# Icon Markers -Icon markers are added using the `addMarkers` or the `addAwesomeMarkers` functions. Their default appearance is a dropped pin. As with most layer functions, the `popup` argument can be used to add a message to be displayed on click, and the `label` option can be used to display a text label either on hover or statically. +Icon markers are added using the `addMarkers()` or the `addAwesomeMarkers()` functions. Their default appearance is a dropped pin. As with most layer functions, the `popup` argument can be used to add a message to be displayed on click, and the `label` option can be used to display a text label either on hover or statically. ```{r} data(quakes) @@ -39,7 +39,7 @@ leaflet(data = quakes[1:20,]) %>% addTiles() %>% addMarkers(~long, ~lat, popup = ~as.character(mag), label = ~as.character(mag)) ``` -#### Customizing Marker Icons +## Customizing Marker Icons You can provide custom markers in one of several ways, depending on the scenario. For each of these ways, the icon can be provided as either a URL or as a file path. @@ -59,7 +59,7 @@ leaflet(data = quakes[1:4,]) %>% addTiles() %>% addMarkers(~long, ~lat, icon = greenLeafIcon) ``` -If you have several icons to apply that vary only by a couple of parameters (i.e. they share the same size and anchor points but have different URLs), use the `icons()` function. `icons()` performs similarly to `data.frame()`, in that any arguments that are shorter than the number of markers will be recycled to fit. +If you have several icons to apply that vary only by a couple of parameters (i.e. they share the same size and anchor points but have different URLs), use `icons()` `icons()` performs similarly to `data.frame()`, in that any arguments that are shorter than the number of markers will be recycled to fit. ```{r fig.height=2} quakes1 <- quakes[1:10,] @@ -80,7 +80,7 @@ leaflet(data = quakes1) %>% addTiles() %>% addMarkers(~long, ~lat, icon = leafIcons) ``` -Finally, if you have a set of icons that vary in multiple parameters, it may be more convenient to use the `iconList()` function. It lets you create a list of (named or unnamed) `makeIcon()` icons, and select from that list by position or name. +Finally, if you have a set of icons that vary in multiple parameters, it may be more convenient to use `iconList()`. It lets you create a list of (named or unnamed) `makeIcon()` icons, and select from that list by position or name. ```{r fig.height=1.75} # Make a list of icons. We'll index into it based on name. @@ -106,14 +106,14 @@ leaflet(df) %>% addTiles() %>% addMarkers(icon = ~oceanIcons[type]) ``` -#### Awesome Icons +## Awesome Icons -Leaflet supports even more customizable markers using the [awesome markers](https://github.com/lvoogdt/Leaflet.awesome-markers) leaflet plugin. +Leaflet supports even more customizable markers using the [awesome markers](https://github.com/lennardv2/Leaflet.awesome-markers) leaflet plugin. -The `addAwesomeMarkers()` function is similar to `addMarkers()` function but additionally allows you to specify custom colors for the markers as well as icons from the [Font Awesome](http://fontawesome.io/icons/), [Bootstrap Glyphicons](https://getbootstrap.com/components/), and [Ion icons](http://ionicons.com/) icon libraries. +The `addAwesomeMarkers()` function is similar to `addMarkers()` function but additionally allows you to specify custom colors for the markers as well as icons from the [Font Awesome](https://fontawesome.com/icons), [Bootstrap Glyphicons](https://getbootstrap.com/components/), and [Ion icons](https://ionic.io/ionicons) icon libraries. -Similar to the `makeIcon`, `icons`, and `iconList` functions described above, you have `makeAwesomeIcon`, `awesomeIcons` and `awesomeIconList` functions, which enable you to add awesome icons. +Similar to `makeIcon()`, `icons()`, and `iconList()` described above, you have `makeAwesomeIcon()`, `awesomeIcons()` and `awesomeIconList()` functions, which enable you to add awesome icons. ```{r} # first 20 quakes @@ -144,7 +144,7 @@ leaflet(df.20) %>% addTiles() %>% The `library` argument has to be one of 'ion', 'fa', or 'glyphicon'. The `icon` argument needs to be the name of any valid icon supported by the the respective library (w/o the prefix of the library name). -#### Marker Clusters +## Marker Clusters When there are a large number of markers on a map, you can cluster them using the [Leaflet.markercluster](https://github.com/Leaflet/Leaflet.markercluster) plug-in. To enable this plug-in, you can provide a list of options to the argument `clusterOptions`, e.g. @@ -154,11 +154,11 @@ leaflet(quakes) %>% addTiles() %>% addMarkers( ) ``` -Using the `freezeAtZoom` argument of the `markerClusterOptions()` function you can set the clustering to freeze as a specific zoom level. For example `markerClusterOptions(freezeAtZoom = 5)` will freeze the cluster at zoom level 5 regardless of the user's actual zoom level. +Using the `freezeAtZoom` argument of `markerClusterOptions()`, you can set the clustering to freeze as a specific zoom level. For example `markerClusterOptions(freezeAtZoom = 5)` will freeze the cluster at zoom level 5 regardless of the user's actual zoom level. -### Circle Markers +# Circle Markers -Circle markers are much like regular circles (see [Lines and Shapes](shapes.html)), except that their radius in onscreen pixels stays constant regardless of zoom level. +Circle markers are much like regular circles (see [Lines and Shapes](https://rstudio.github.io/leaflet/articles/shapes.html)), except that their radius in onscreen pixels stays constant regardless of zoom level. You can use their default appearance: diff --git a/vignettes/articles/morefeatures.Rmd b/vignettes/articles/morefeatures.Rmd index efa9fbd65..796368597 100644 --- a/vignettes/articles/morefeatures.Rmd +++ b/vignettes/articles/morefeatures.Rmd @@ -1,9 +1,13 @@ --- -title: "More features" +title: "Additional features" --- - -## Additional features +```{r, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>" +) +``` - Add-ons - [Leaflet Measure](#leaflet-measure) @@ -12,17 +16,17 @@ title: "More features" - [Minimap](#minimap) - [EasyButton](#easybutton) - Advanced Features - - [Custom JavaScript with `htmlwidgets::onRender`](#custom-javascript-with-htmlwidgetonrender) + - [Custom JavaScript with `htmlwidgets::onRender()`](#custom-javascript-with-htmlwidgetonrender) -### Add-ons +# Add-ons These are various utility functions that you can use to augment your map with additional elements. Each of the utility function give below supports options of customization, be sure to check the help files for details. -#### Leaflet Measure +## Leaflet Measure You can use `addMeasure()` to add the [leaflet-measure](https://github.com/ljagis/leaflet-measure) plugin to a map. -```{r } +```{r} library(leaflet) m <- leaflet() %>% addTiles() @@ -35,7 +39,7 @@ m %>% Use various options to customize the appearance and behavior of the plugin (see `?addMeasure` for details). -```{r } +```{r} m %>% # Berlin, Germany fitBounds(13.76134, 52.675499, 13.0884, 52.33812) %>% @@ -47,11 +51,11 @@ m %>% completedColor = "#7D4479") ``` -#### Graticule +## Graticule -Use the `addGraticule` function to add a graticule (grid) to the map (via the [Leaflet.Graticule](https://github.com/turban/Leaflet.Graticule) plugin). +Use `addGraticule()` to add a graticule (grid) to the map (via the [Leaflet.Graticule](https://github.com/turban/Leaflet.Graticule) plugin). -```{r } +```{r} library(leaflet) m <- leaflet() %>% addTiles() %>% setView(0,0,2) @@ -62,14 +66,14 @@ m %>% addGraticule(interval = 40, style = list(color = "#FF0000", weight = 1)) You can use the `group` argument to make the graticule toggleable. -```{r } +```{r} m %>% addGraticule(group = "Graticule") %>% addLayersControl(overlayGroups = c("Graticule"), options = layersControlOptions(collapsed = FALSE)) ``` -#### Terminator (day/night indicator) +## Terminator (day/night indicator) ```{r} library(leaflet) @@ -89,13 +93,13 @@ leaflet() %>% options = layersControlOptions(collapsed = FALSE)) ``` -#### Minimap +## Minimap -You can use the `addMiniMap()` function to add a minimap to aid in navigation. This is implemented via the [Leaflet-MiniMap](https://github.com/Norkart/Leaflet-MiniMap) plugin. +You can use `addMiniMap()` to add a minimap to aid in navigation. This is implemented via the [Leaflet-MiniMap](https://github.com/Norkart/Leaflet-MiniMap) plugin. Note that the minimap only shows map tiles; markers, polygons, and other layers on the main map will not be displayed in the minimap. -```{r } +```{r} library(leaflet) l <- leaflet() %>% setView(0,0,3) @@ -106,7 +110,7 @@ l %>% You can use a specific basemap for the minimap via the `tiles` parameter. This example also allows the minimap to be hidden by setting `toggleDisplay = TRUE`. -```{r } +```{r} l %>% addProviderTiles(providers$Esri.WorldStreetMap) %>% addMiniMap( @@ -114,11 +118,11 @@ l %>% toggleDisplay = TRUE) ``` -#### EasyButton +## EasyButton Use `addEasyButton()` to add simple buttons (via [Leaflet.EasyButton](https://github.com/CliffCloud/Leaflet.EasyButton)) that trigger custom JavaScript logic. -```{r } +```{r} library(leaflet) library(htmltools) library(htmlwidgets) @@ -126,7 +130,7 @@ library(htmlwidgets) This map adds two buttons: one sets the map zoom level to 1, and the other attempts to locate you. -```{r } +```{r} leaflet() %>% addTiles() %>% addEasyButton(easyButton( icon="fa-globe", title="Zoom to Level 1", @@ -173,11 +177,11 @@ leaflet() %>% addTiles() %>% )) ``` -### Advanced Features +# Advanced Features -#### Custom JavaScript with `htmlwidgets::onRender` +## Custom JavaScript with `htmlwidgets::onRender()` -The `htmlwidgets::onRender` function can be used to add custom behavior to the leaflet map using native Javascript. This is a some what advanced use case and requires you to know Javascript. Using `onRender` you can customize your map's behavior using any of the APIs as defined in the Leaflet.js [documentation](https://leafletjs.com/reference.html). +`htmlwidgets::onRender()` can be used to add custom behavior to the leaflet map using native Javascript. This is a some what advanced use case and requires you to know Javascript. Using `onRender` you can customize your map's behavior using any of the APIs as defined in the Leaflet.js [documentation](https://leafletjs.com/reference.html). Below is an example where we sync the base layer of the mini-map with the baselayer of the main map, using the 'baselayerchange' event. diff --git a/vignettes/articles/popups.Rmd b/vignettes/articles/popups.Rmd index b27f8057c..718c7b94c 100644 --- a/vignettes/articles/popups.Rmd +++ b/vignettes/articles/popups.Rmd @@ -21,7 +21,7 @@ Use the `addPopups()` function to add standalone popup to the map. ```{r} content <- paste(sep = "
", - "Samurai Noodle", + "Samurai Noodle", "606 5th Ave. S", "Seattle, WA 98138" ) @@ -79,19 +79,19 @@ leaflet() %>% addTiles() %>% setView(-118.456554, 34.09, 13) %>% addMarkers( lng = -118.456554, lat = 34.105, label = "Default Label", - labelOptions = labelOptions(noHide = T)) %>% + labelOptions = labelOptions(noHide = TRUE)) %>% addMarkers( lng = -118.456554, lat = 34.095, label = "Label w/o surrounding box", - labelOptions = labelOptions(noHide = T, textOnly = TRUE)) %>% + labelOptions = labelOptions(noHide = TRUE, textOnly = TRUE)) %>% addMarkers( lng = -118.456554, lat = 34.085, label = "label w/ textsize 15px", - labelOptions = labelOptions(noHide = T, textsize = "15px")) %>% + labelOptions = labelOptions(noHide = TRUE, textsize = "15px")) %>% addMarkers( lng = -118.456554, lat = 34.075, label = "Label w/ custom CSS style", - labelOptions = labelOptions(noHide = T, direction = "bottom", + labelOptions = labelOptions(noHide = TRUE, direction = "bottom", style = list( "color" = "red", "font-family" = "serif", diff --git a/vignettes/articles/projections.Rmd b/vignettes/articles/projections.Rmd index 266b567e4..004a5db47 100644 --- a/vignettes/articles/projections.Rmd +++ b/vignettes/articles/projections.Rmd @@ -13,17 +13,17 @@ knitr::opts_chunk$set( library(leaflet) ``` -**Note:** This functionality is for advanced users and may not be supported across all functions (for example, `addRasterImage` currently works only with EPSG:3857 Web Mercator). +**Note:** This functionality is for advanced users and may not be supported across all functions (for example, `addRasterImage()` currently works only with EPSG:3857 Web Mercator). -The Leaflet package expects all point, line, and shape data to be specified in latitude and longitude using WGS 84 (a.k.a. EPSG:4326). By default, when displaying this data it projects everything to [EPSG:3857](http://epsg.io/3857) and expects that any map tiles are also displayed in EPSG:3857. +The Leaflet package expects all point, line, and shape data to be specified in latitude and longitude using WGS 84 (a.k.a. EPSG:4326). By default, when displaying this data it projects everything to [EPSG:3857](https://spatialreference.org/ref/epsg/3857/) and expects that any map tiles are also displayed in EPSG:3857. For users that need to display data with a different projection, we've integrated the [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin, which in theory gives Leaflet access to any CRS that is supported by [Proj4js](http://proj4js.org/). Note that whatever map tiles you use _must_ be designed to work with the CRS of your Leaflet map. -### Defining a custom CRS +# Defining a custom CRS -Once you've decided on a custom projection, and have map tiles to match it (if necessary), you can use the `leafletCRS` function to create a custom projection. +Once you've decided on a custom projection, and have map tiles to match it (if necessary), you can use `leafletCRS()` to create a custom projection. ```{r} crs <- leafletCRS(crsClass = "L.Proj.CRS", code = "ESRI:102003", @@ -35,11 +35,11 @@ The `crsClass` parameter lets you specify the JavaScript constructor to use to g The `code` parameter is the CRS identifier, usually an EPSG identifier or similar. (For the most part, this doesn't affect us, and you can treat it like documentation; it's primarily used by Proj4Leaflet for purposes that don't apply to the R package.) -The `proj4def` parameter is either a PROJ.4 or WKT string that defines the CRS. If you don't know the PROJ.4 or WKT string, you can generally find these on [epsg.io](https://epsg.io/) or [spatialreference.org](http://spatialreference.org/). +The `proj4def` parameter is either a PROJ.4 or WKT string that defines the CRS. If you don't know the PROJ.4 or WKT string, you can generally find these on [epsg.io](https://epsg.io/) or [spatialreference.org](https://spatialreference.org/). The resulting object can be passed to the `leaflet` function via the parameter `crs = leafletOptions(crs = ...)`. -### Displaying basemap tiles with custom projections +# Displaying basemap tiles with custom projections This example shows Gothenberg, Sweden in [EPSG:3006](http://epsg.io/3006) (SWEREF99 TM) projection. @@ -53,15 +53,15 @@ epsg3006 <- leafletCRS(crsClass = "L.Proj.CRS", code = "EPSG:3006", tile_url <- "http://api.geosition.com/tile/osm-bright-3006/{z}/{x}/{y}.png" tile_attrib <- "Map data © OpenStreetMap contributors, Imagery © 2013 Kartena" -leaflet(options = leafletOptions(worldCopyJump = F, crs = epsg3006)) %>% +leaflet(options = leafletOptions(worldCopyJump = FALSE, crs = epsg3006)) %>% setView(11.965053, 57.70451, 13) %>% addTiles(urlTemplate = tile_url, attribution = tile_attrib, - options = tileOptions(minZoom = 0, maxZoom = 14, continuousWorld = T)) %>% + options = tileOptions(minZoom = 0, maxZoom = 14, continuousWorld = TRUE)) %>% addMarkers(11.965053, 57.70451) ``` -Again, it's critical to use basemap tiles that are in the same projection that is specified in the `leafletCRS` function. In this case the api.geosition.com server does indeed uses EPSG:3006 for its tiles. +Again, it's critical to use basemap tiles that are in the same projection that is specified in `leafletCRS()`. In this case the api.geosition.com server does indeed uses EPSG:3006 for its tiles. We can render a similar map with the default EPSG:3857 projection for comparison. If the custom projection worked correctly, the markers should appear at the same position. @@ -72,11 +72,11 @@ leaflet() %>% addMarkers(11.965053, 57.70451) ``` -### Displaying shapes with custom projections +# Displaying shapes with custom projections -While tiles must be in the same projection as used in the `leafletCRS` function, you must always use WGS 84 longitude/latitude data for markers, circles, polygons, and lines. Leaflet will automatically project the coordinates when displaying. +While tiles must be in the same projection as used in `leafletCRS()`, you must always use WGS 84 longitude/latitude data for markers, circles, polygons, and lines. Leaflet will automatically project the coordinates when displaying. -This example uses [EPSG:2163](http://epsg.io/2163) (US National Atlas Equal Area projection). The dataset we use (`usa_sf` from the `albersusa` package, though we're not actually using Albers projection here) has Alaska and Hawaii moved closer to mainland US as well as rotated and resized accordingly. +This example uses [EPSG:2163](https://epsg.io/2163) (US National Atlas Equal Area projection). The dataset we use (`usa_sf` from the `albersusa` package, though we're not actually using Albers projection here) has Alaska and Hawaii moved closer to mainland US as well as rotated and resized accordingly. ```{r message=FALSE,warning=FALSE,eval=FALSE} library(sp) @@ -96,6 +96,8 @@ leaflet(spdf, options = leafletOptions(crs = epsg2163)) %>% labelOptions = labelOptions(direction = "auto")) ``` -### Polar projections +# Polar projections -It's possible to use polar projections, though you may encounter even more problems and incompatibilities with other Leaflet.js plugins than when using other types of custom projections. You can refer to [this set of examples](http://rpubs.com/bhaskarvk/leaflet-polarmaps) by Bhaskar Karambelkar to get started. +It's possible to use polar projections, though you may encounter even more problems and incompatibilities with other Leaflet.js plugins than when using other types of custom projections. + + diff --git a/vignettes/articles/raster.Rmd b/vignettes/articles/raster.Rmd index e83c536d5..de676d269 100644 --- a/vignettes/articles/raster.Rmd +++ b/vignettes/articles/raster.Rmd @@ -9,9 +9,9 @@ knitr::opts_chunk$set( ) ``` -Two-dimensional `SpatRaster` objects (from the [`terra` package](https://CRAN.R-project.org/package=terra)) or `RasterLayer` objects (from the [`raster` package](https://CRAN.R-project.org/package=raster)) can be turned into images and added to Leaflet maps using the `addRasterImage` function. +Two-dimensional `SpatRaster` objects (from the [`terra` package](https://CRAN.R-project.org/package=terra)) or `RasterLayer` objects (from the [`raster` package](https://CRAN.R-project.org/package=raster)) can be turned into images and added to Leaflet maps using `addRasterImage()`. -The `addRasterImage` function works by projecting the `SpatRaster` or `RasterLayer` object to [EPSG:3857](http://spatialreference.org/ref/sr-org/7483/) and encoding each cell to an RGBA color, to produce a PNG image. That image is then embedded in the map widget. +`addRasterImage()` works by projecting the `SpatRaster` or `RasterLayer` object to [EPSG:3857](https://spatialreference.org/ref/epsg/3857/) and encoding each cell to an RGBA color, to produce a PNG image. That image is then embedded in the map widget. It's important that the raster object is tagged with a proper coordinate reference system. Many raster files contain this information, but some do not. Here is how you'd tag a raster object "`r`" which contains WGS84 data: @@ -19,27 +19,27 @@ It's important that the raster object is tagged with a proper coordinate referen crs(r) <- "+proj=longlat +datum=WGS84" ``` -### Large Raster Warning +# Large Raster Warning -Because the `addRasterImage` function embeds the image in the map widget, it will increase the size of the generated HTML proportionally. In order to avoid unacceptable download times and memory usage, `addRasterImage` will error when the PNG is beyond the size indicated by the `maxBytes` argument (defaults to 4 megabytes). +Because `addRasterImage()` embeds the image in the map widget, it will increase the size of the generated HTML proportionally. In order to avoid unacceptable download times and memory usage, `addRasterImage()` will error when the PNG is beyond the size indicated by the `maxBytes` argument (defaults to 4 megabytes). -If you have a large raster layer, you can provide a larger number of bytes and see how it goes, or use `terra::resample`, `raster::resample`, or `raster::aggregate` to decrease the number of cells. +If you have a large raster layer, you can provide a larger number of bytes and see how it goes, or use `terra::resample()`, `raster::resample()`, or `raster::aggregate()` to decrease the number of cells. -### Projection Performance +# Projection Performance -The `addRasterImage` function projects using `terra::project` or `raster::projectRaster`, which can take a while on all but the smallest rasters. If you have a large raster layer or expect to call `addRasterImage` on the same raster layer many times, you can perform the [EPSG:3857](http://spatialreference.org/ref/sr-org/7483/) projection yourself (either using `leaflet::projectRasterForLeaflet` or using another GIS library or program) and call `addRasterImage` with `project = FALSE`. +`addRasterImage()` projects using `terra::project()` or `raster::projectRaster()`, which can take a while on all but the smallest rasters. If you have a large raster layer or expect to call `addRasterImage()` on the same raster layer many times, you can perform the [EPSG:3857](https://spatialreference.org/ref/epsg/3857/) projection yourself (either using `leaflet::projectRasterForLeaflet()` or using another GIS library or program) and call `addRasterImage()` with `project = FALSE`. Be sure that your pre-projected raster layer is tagged with an accurate extent and CRS, as these values are still needed to place the image in the proper position on the map. -### Coloring +# Coloring In order to render the raster object as an image, each cell value must be converted to an RGB(A) color. You can specify the color scale using the `colors` argument, which accepts a variety of color specifications: -* The name of a [Color Brewer 2](http://colorbrewer2.org/) palette. If no `colors` argument is provided, then `"Spectral"` is the default. -* A vector that represents the ordered list of colors to map to the data. Any color specification that is accepted by `grDevices::col2rgb` can be used, including `"#RRGGBB"` and `"#RRGGBBAA"` forms. Example: `colors = c("#E0F3DB", "#A8DDB5", "#43A2CA")`. -* A color scaling function, like those detailed in the [Colors](colors.html) topic. For example: `colors = colorBin("Greens", domain = NULL, bins = 5, na.color = "transparent")`. +* The name of a [Color Brewer 2](https://colorbrewer2.org/) palette. If no `colors` argument is provided, then `"Spectral"` is the default. +* A vector that represents the ordered list of colors to map to the data. Any color specification that is accepted by `grDevices::col2rgb()` can be used, including `"#RRGGBB"` and `"#RRGGBBAA"` forms. Example: `colors = c("#E0F3DB", "#A8DDB5", "#43A2CA")`. +* A color scaling function, like those detailed in the [Colors](https://rstudio.github.io/leaflet/articles/colors.html) topic. For example: `colors = colorBin("Greens", domain = NULL, bins = 5, na.color = "transparent")`. -### Example +# Example ```{r echo=FALSE} suppressPackageStartupMessages({ @@ -53,7 +53,7 @@ library(leaflet) ```{r eval=FALSE} library(raster) library(leaflet) -r <- raster("nc/oisst-sst.nc") +r <- raster("https://rstudio.github.io/leaflet/nc/oisst-sst.nc") ``` ```{r} diff --git a/vignettes/articles/shiny.Rmd b/vignettes/articles/shiny.Rmd index 030ddea91..0cf4ef724 100644 --- a/vignettes/articles/shiny.Rmd +++ b/vignettes/articles/shiny.Rmd @@ -10,11 +10,11 @@ knitr::opts_chunk$set( ``` -*Shiny is a web framework for R. To learn more about Shiny, visit [shiny.rstudio.com](http://shiny.rstudio.com/).* +*Shiny is a web framework for R and Python. To learn more about Shiny, visit the [shiny website](https://shiny.posit.co/).* The Leaflet package includes powerful and convenient features for integrating with Shiny applications. -Most Shiny output widgets are incorporated into an app by including an output (e.g. `plotOutput`) for the widget in the UI definition, and using a render function (e.g. `renderPlot`) in the server function. Leaflet maps are no different; in the UI you call `leafletOutput`, and on the server side you assign a `renderLeaflet` call to the output. Inside the `renderLeaflet` expression, you return a Leaflet map object. +Most Shiny output widgets are incorporated into an app by including an output (e.g. `plotOutput()`) for the widget in the UI definition, and using a render function (e.g. `renderPlot()`) in the server function. Leaflet maps are no different; in the UI you call `leafletOutput()`, and on the server side you assign a `renderLeaflet()` call to the output. Inside the `renderLeaflet()` expression, you return a Leaflet map object. ```{r eval=FALSE} library(shiny) @@ -49,15 +49,15 @@ shinyApp(ui, server) ![Screenshot of a simple Shiny app](images/shiny1.png) -### Modifying Existing Maps with `leafletProxy` +# Modifying Existing Maps with `leafletProxy` -This works, but reactive inputs and expressions that affect the `renderLeaflet` expression will cause the entire map to be redrawn from scratch and reset the map position and zoom level. +This works, but reactive inputs and expressions that affect the `renderLeaflet()` expression will cause the entire map to be redrawn from scratch and reset the map position and zoom level. For some situations that may be acceptable or desirable behavior. But in other situations, you may want finer-grained control over the map, such as changing the color of a single polygon or adding a marker at the point of a click -- without redrawing the entire map. To modify a map that's already running in the page, you use the `leafletProxy()` function in place of the `leaflet()` call, but otherwise use Leaflet function calls as normal. -Normally you use `leaflet` to create the static aspects of the map, and `leafletProxy` to manage the dynamic elements, like so: +Normally you use `leaflet` to create the static aspects of the map, and `leafletProxy()` to manage the dynamic elements, like so: ```{r eval=FALSE} library(shiny) @@ -152,30 +152,30 @@ proxy %>% removeShape(c("B", "F")) proxy %>% clearShapes() ``` -### Understanding Layer IDs +# Understanding Layer IDs -Layer IDs can be used to replace or remove specific map elements. (**Note:** For managing groups of map elements, see the [Show/Hide Layers](showhide.html) topic.) +Layer IDs can be used to replace or remove specific map elements. (**Note:** For managing groups of map elements, see the [Show/Hide Layers](https://rstudio.github.io/leaflet/articles/showhide.html) topic.) When you give an object a layer ID, if a similar object exists with the same ID, it will be removed from the map when the new object is added. All layer-adding functions take a `layerId` argument. Generally this is a vectorized argument; if adding 50 polygons, you'll need to pass either `NULL` or a 50-element character vector as your `layerId` value. (If you use a single-element character vector as your `layerId`, then all of the 50 polygons will have the same ID, and all but the last polygon will be removed; so don't do that!) -Layer IDs are namespaced by category. Layer IDs only need be unique within their category; a call to `addCircles` will not cause any tile layers to be removed, regardless of layer ID, because circles and tiles are in different categories. +Layer IDs are namespaced by category. Layer IDs only need be unique within their category; a call to `addCircles()` will not cause any tile layers to be removed, regardless of layer ID, because circles and tiles are in different categories. Category | Add functions | Remove | Clear -------------- | -------------------------------------------------------------- | --------------- | --------------- -tile | `addTiles`, `addProviderTiles` | `removeTiles` | `clearTiles` -marker | `addMarkers`, `addCircleMarkers` | `removeMarker` | `clearMarkers` -shape | `addPolygons`, `addPolylines`, `addCircles`, `addRectangles` | `removeShape` | `clearShapes` -geojson | `addGeoJSON` | `removeGeoJSON` | `clearGeoJSON` -topojson | `addTopoJSON` | `removeTopoJSON` | `clearTopoJSON` -control | `addControl` | `removeControl` | `clearControls` +tile | `addTiles()`, `addProviderTiles()` | `removeTiles()` | `clearTiles()` +marker | `addMarkers()`, `addCircleMarkers()` | `removeMarker()`| `clearMarkers()` +shape | `addPolygons()`, `addPolylines()`, `addCircles()`, `addRectangles()` | `removeShape()` | `clearShapes()` +geojson | `addGeoJSON()` | `removeGeoJSON()` | `clearGeoJSON()` +topojson | `addTopoJSON()` | `removeTopoJSON()` | `clearTopoJSON()` +control | `addControl()` | `removeControl()` | `clearControls()` -### Inputs/Events +# Inputs/Events Leaflet maps and objects send input values (which we'll refer to as "events" in this document) to Shiny as the user interacts with them. -#### Object events +## Object events Object event names generally use this pattern: @@ -198,7 +198,7 @@ GeoJSON events also include additional properties: * `featureId` - The feature ID, if any * `properties` - The feature properties -#### Map events +## Map events The map itself also has a few input values/events. @@ -206,12 +206,12 @@ The map itself also has a few input values/events. input$*MAPID*\_bounds provides the latitude/longitude bounds of the currently visible map area; the value is a `list()` that has named elements `north`, `east`, `south`, and `west`. -input$*MAPID*\_zoom is an integer that indicates the [zoom level](http://wiki.openstreetmap.org/wiki/Zoom_levels). +input$*MAPID*\_zoom is an integer that indicates the [zoom level](https://wiki.openstreetmap.org/wiki/Zoom_levels). -input$*MAPID*\_center provides the latitude/longtitude of the center of the currently visible map area; the value is a `list()` that has named elements `lat` and `lng`. +input$*MAPID*\_center provides the latitude/longitude of the center of the currently visible map area; the value is a `list()` that has named elements `lat` and `lng`. -### Putting it all together +# Putting it all together -For an extensive example of Shiny and Leaflet working together, take a look at the [SuperZip Explorer](http://shiny.rstudio.com/gallery/superzip-example.html) example app (note the "Get Code" button at the top of the page). (Hint: Try clicking on the bubbles, and also notice that the plots in the sidebar change as you pan and zoom around the map.) +For an extensive example of Shiny and Leaflet working together, take a look at the [SuperZip Explorer](https://shiny.posit.co/r/gallery/interactive-visualizations/superzip-example/) example app (note the "Get Code" button at the top of the page). (Hint: Try clicking on the bubbles, and also notice that the plots in the sidebar change as you pan and zoom around the map.) -[![Screenshot of SuperZip Explorer example app](images/shiny3.png)](http://shiny.rstudio.com/gallery/superzip-example.html) +[![Screenshot of SuperZip Explorer example app](images/shiny3.png)](https://shiny.posit.co/r/gallery/interactive-visualizations/superzip-example/) diff --git a/vignettes/articles/showhide.Rmd b/vignettes/articles/showhide.Rmd index 1e5763a6b..9763a4f1f 100644 --- a/vignettes/articles/showhide.Rmd +++ b/vignettes/articles/showhide.Rmd @@ -14,13 +14,11 @@ library(leaflet) library(magrittr) ``` -## Show/Hide Layers - -The Leaflet package includes functions to show and hide map layers. You can allow users to decide what layers to show and hide, or programmatically control the visibility of layers using [server-side code in Shiny](shiny.html). +The Leaflet package includes functions to show and hide map layers. You can allow users to decide what layers to show and hide, or programmatically control the visibility of layers using [server-side code in Shiny](https://rstudio.github.io/leaflet/articles/shiny.html). In both cases, the fundamental unit of showing/hiding is the **group**. -### Understanding Groups +# Understanding Groups A group is a label given to a set of layers. You assign layers to groups by using the `group` parameter when adding the layers to the map. @@ -39,15 +37,15 @@ Many layers can belong to same group. But each layer can only belong to zero or

Groups vs. Layer IDs

-Groups and [Layer IDs](shiny.html#understanding-layer-ids) may appear similar, in that both are used to assign a name to a layer. However, they differ in that layer IDs are used to provide a *unique identifier* to *individual* markers and shapes, etc., while groups are used to give *shared labels* to *many* items. +Groups and [Layer IDs](https://rstudio.github.io/leaflet/articles/shiny.html#understanding-layer-ids) may appear similar, in that both are used to assign a name to a layer. However, they differ in that layer IDs are used to provide a *unique identifier* to *individual* markers and shapes, etc., while groups are used to give *shared labels* to *many* items. -You generally provide one `group` value for the entire `addMarkers` call, and you can reuse that same `group` value in future `addXXX` calls to add to that group's membership (as in the example above). +You generally provide one `group` value for the entire `addMarkers()` call, and you can reuse that same `group` value in future `add*()` calls to add to that group's membership (as in the example above). -`layerId` arguments are *always* vectorized: when calling e.g. `addMarkers` you need to provide one layer ID per marker, and they must all be unique. If you add a circle with a layer ID of `"foo"` and later add a different shape with the same layer ID, the original circle will be removed. +`layerId` arguments are *always* vectorized: when calling e.g. `addMarkers()` you need to provide one layer ID per marker, and they must all be unique. If you add a circle with a layer ID of `"foo"` and later add a different shape with the same layer ID, the original circle will be removed.
-### Interactive Layer Display +# Interactive Layer Display You can use Leaflet's layers control feature to allow users to toggle the visibility of groups. @@ -60,9 +58,9 @@ map <- leaflet(quakes) %>% addProviderTiles(providers$Stadia.StamenToner, group = "Toner") %>% addProviderTiles(providers$Stadia.StamenTonerLite, group = "Toner Lite") %>% # Overlay groups - addCircles(~long, ~lat, ~10^mag/5, stroke = F, group = "Quakes") %>% + addCircles(~long, ~lat, ~10^mag/5, stroke = FALSE, group = "Quakes") %>% addPolygons(data = outline, lng = ~long, lat = ~lat, - fill = F, weight = 2, color = "#FFFFCC", group = "Outline") %>% + fill = FALSE, weight = 2, color = "#FFFFCC", group = "Outline") %>% # Layers control addLayersControl( baseGroups = c("OSM (default)", "Toner", "Toner Lite"), @@ -72,27 +70,27 @@ map <- leaflet(quakes) %>% map ``` -The `addLayersControl` function distinguishes between *base groups*, which can only be viewed one group at a time, and *overlay groups*, which can be individually checked or unchecked. +`addLayersControl()` distinguishes between *base groups*, which can only be viewed one group at a time, and *overlay groups*, which can be individually checked or unchecked. Although base groups are generally tile layers, and overlay groups are usually markers and shapes, there is no restriction on what types of layers can be placed in each category. -Only one layers control can be present on a map at a time. If you call `addLayersControl` multiple times, the last call will win. +Only one layers control can be present on a map at a time. If you call `addLayersControl()` multiple times, the last call will win. -### Programmatic Layer Display +# Programmatic Layer Display -You can use the `showGroup` and `hideGroup` functions to show and hide groups from code. This mostly makes sense in a [Shiny context with `leafletProxy`](shiny.html), where perhaps you might toggle group visibility based on input controls in a sidebar. +You can use `showGroup()` and `hideGroup()` to show and hide groups from code. This mostly makes sense in a [Shiny context with `leafletProxy`](https://rstudio.github.io/leaflet/articles/shiny.html), where perhaps you might toggle group visibility based on input controls in a sidebar. -You can also use `showGroup`/`hideGroup` in conjuction with `addLayersControl` to set which groups are checked by default. +You can also use `showGroup()`/`hideGroup()` in conjunction with `addLayersControl()` to set which groups are checked by default. ```{r} map %>% hideGroup("Outline") ``` -Finally, you can remove the layers in a group using `clearGroup`. Note that this doesn't just remove the layers from the group, it also removes them from the map. (It does not, however, remove the group itself from the map; it still exists, but is empty.) +Finally, you can remove the layers in a group using `clearGroup()`. Note that this doesn't just remove the layers from the group, it also removes them from the map. (It does not, however, remove the group itself from the map; it still exists, but is empty.) -## With Marker Clusters +# With Marker Clusters -If markers are added to different groups, and when using marker clustering as described in the [marker](markers.html) page, leaflet will generate different sets of clusters for different groups. This allows showing/hiding of marker clusters belonging to a group independently of other marker clusters in other groups. +If markers are added to different groups, and when using marker clustering as described in the [marker](https://rstudio.github.io/leaflet/articles/markers.html) page, leaflet will generate different sets of clusters for different groups. This allows showing/hiding of marker clusters belonging to a group independently of other marker clusters in other groups. ```{r} @@ -112,8 +110,8 @@ names(quakes.df) %>% label=~as.character(mag), popup=~as.character(mag), group = df, - clusterOptions = markerClusterOptions(removeOutsideVisibleBounds = F), - labelOptions = labelOptions(noHide = F, + clusterOptions = markerClusterOptions(removeOutsideVisibleBounds = FALSE), + labelOptions = labelOptions(noHide = FALSE, direction = 'auto')) }) diff --git a/vignettes/articles/widget.Rmd b/vignettes/articles/widget.Rmd index 529bee10f..c42760d39 100644 --- a/vignettes/articles/widget.Rmd +++ b/vignettes/articles/widget.Rmd @@ -9,9 +9,9 @@ knitr::opts_chunk$set( ) ``` -The function `leaflet()` returns a Leaflet map widget, which stores a list of objects that can be modified or updated later. Most functions in this package have an argument `map` as their first argument, which makes it easy to use the pipe operator `%>%` in the **magrittr** package, as you have seen from the example in the [Introduction](./). +The function `leaflet()` returns a Leaflet map widget, which stores a list of objects that can be modified or updated later. Most functions in this package have an argument `map` as their first argument, which makes it easy to use the pipe operator `%>%` in the **magrittr** package, as you have seen from the example in `vignette("leaflet")`. -### Initializing Options +# Initializing Options The map widget can be initialized with certain parameters. This is achieved by populating the `options` argument as shown below. ```{r, include = FALSE} @@ -25,9 +25,9 @@ library(magrittr) leaflet(options = leafletOptions(minZoom = 0, maxZoom = 18)) ``` -The `leafletOptions()` can be passed any option described in the leaflet [reference document](https://web.archive.org/web/20220702182250/https://leafletjs.com/reference-1.3.4.html#map-option). Using the `leafletOptions()`, you can set a custom [CRS](https://en.wikipedia.org/wiki/Spatial_reference_system) and have your map displayed in a non spherical mercator projection as described in [projections](projections.html). +The `leafletOptions()` can be passed any option described in the leaflet [reference document](https://web.archive.org/web/20220702182250/https://leafletjs.com/reference-1.3.4.html#map-option). Using the `leafletOptions()`, you can set a custom [CRS](https://en.wikipedia.org/wiki/Spatial_reference_system) and have your map displayed in a non spherical mercator projection as described in [projections](https://rstudio.github.io/leaflet/articles/projections.html). -### Map Methods +# Map Methods You can manipulate the attributes of the map widget using a series of methods. Please see the help page `?setView` for details. @@ -35,20 +35,20 @@ You can manipulate the attributes of the map widget using a series of methods. P - `fitBounds()` fits the view into the rectangle `[lng1, lat1]` -- `[lng2, lat2]`; - `clearBounds()` clears the bound, so that the view will be automatically determined by the range of latitude/longitude data in the map layers if provided; -### The Data Object +# The Data Object Both `leaflet()` and the map layer functions have an optional `data` parameter that is designed to receive spatial data in one of several forms: - From base R: - lng/lat matrix - data frame with lng/lat columns -- From the [**sp** package](http://cran.rstudio.com/package=sp): +- From the [**sp** package](https://cran.rstudio.com/package=sp): - `SpatialPoints[DataFrame]` - `Line`/`Lines` - `SpatialLines[DataFrame]` - `Polygon`/`Polygons` - `SpatialPolygons[DataFrame]` -- From the [**maps** package](http://cran.rstudio.com/package=maps): +- From the [**maps** package](https://cran.rstudio.com/package=maps): - the data frame from returned from `map()` The `data` argument is used to derive spatial data for functions that need it; for example, if `data` is a `SpatialPolygonsDataFrame` object, then calling `addPolygons` on that map widget will know to add the polygons from that `SpatialPolygonsDataFrame`. @@ -101,7 +101,7 @@ leaflet(data = mapStates) %>% addTiles() %>% ``` -### The Formula Interface +# The Formula Interface The arguments of all layer functions can take normal R objects, such as a numeric vector for the `lat` argument, or a character vector of colors for the `color` argument. They can also take a one-sided formula, in which case the formula will be evaluated using the `data` argument as the environment. For example, `~ x` means the variable `x` in the data object, and you can write arbitrary expressions on the right-hand side, e.g., `~ sqrt(x + 1)`.