Learn the basics of {leaflet} using my RWB data as practical example
3.1 Preliminary remark
After following Making maps with R (chapter 9 of the online book Geocomputation with R) and making my own research (see my notes in Chapter 2) it turned out that {leaflet} / leaflet.js is the most mature and widely used interactive mapping package in R interactive map drawing software. {leaflet} has twice more downloads than {tmap} which is as the moment the leading spatial geographic map tool. (See Listing / Output 3.1 which contains a list of downloads for several map drawing packages.)
I just learned in the section Section 3.3.3 that {maps} is another important package ranking with it download numbers in the second place!
I added this package therefore to Listing / Output 3.1. The above paragraph is not correct anymore as {maps} has about 50% more downloads than {leaflet}.
R Code 3.1 : Overview of download numbers of map packages
Listing / Output 3.1: Overview of download numbers of map packages
Code
my_pkgs_dl( pkgs =c("tmap", "plotly", "mapview","mapdeck","googleway","mapsf","mapmisc","leaflet","Rgooglemaps","ggmap","mapedit","ggiraph","maps"), period ="last-month", days =30)
Although {leaflet} has with about 3.000 downloads/day only about the half of the {plotly} downloads it is a specialized map drawing software whereas {plotly} is a general interactive web graphics tool.
It’s worth noting that {plotly} aims to be a general purpose visualization library, and thus, doesn’t aim to be the most fully featured geo-spatial visualization toolkit. That said, there are benefits to using {plotly}-based maps since the mapping APIs are very similar to the rest of {plotly}, and you can leverage larger {plotly} ecosystem (e.g., linking views client side … ). However, if you run into limitations with {plotly}’s mapping functionality, there is a very rich set of tools for interactive geospatial visualization in R, including but not limited to: {leaflet}, {mapview}, {mapedit}, {tmap}, and {mapdeck} (Robin Lovelace 2019). Quoted from chapter 4 of (Sievert 2019).
Another option to consider would be to use ggplot2::geom_sf() together with
plotly::ggplotly() or Hmisc::ggpltlyr() (Converts a ggplot2::ggplot() object to a {plotly} object, in {Hmisc} variant removes extraneous text that ggplotly() puts in hover text)
{ggspatial} (Spatial Data Framework for ‘ggplot2’)
{geofacet} (‘ggplot2’ Faceting Utilities for Geographical Data) This has the advantage that I am using with {ggplot2} known territory. But in this chapter I will focus on {leaflet}.
Resource 3.1 : Leaflet resources on the Internet
I am ignoring to list tutorials using Leaflet.js from scratch and collect here only resources for learning the R {leaflet} package. Many tutorials cover some special actions like adding markers but my special focus at the moment is on choropleth maps.
Most important resources
An R Interface to Leaflet Maps: Official package documentation with a getting started page and several article covering a specific subject. I will start to learn the R leaflet package with this authoritative resource!
Package {leaflet}: Official documentation in one page. Sorted not by function name but by short description. Helpful for looking up the name & syntax of a function for a specific problem. Last updated 2025-07-30.
library(leaflet)m<-leaflet()|># (1) Create the ma widget addTiles()|># (2) Add default OpenStreetMap map tilesaddMarkers(lng =174.768, # (3) Add another element to the map lat =-36.852, popup ="The birthplace of R")m# (4) Print the map
Graph 3.1: A basic R leaflet example. Click at the marker to see what it indicates.
3.2.3 Next step
The {leaflet} tutorial highly recommends to start with the article The Map Widget before exploring the rest of the site. It is the first article under the menu “Articles”. It seems to me that the best way to learn leaflet is to proceed with the offered article in their sequence from top to the bottom of the menu.
Watch out! 3.1: {leaflet} Documentation refers to leaflet.js version 1.34
The links to the details leaflet.js documentation refers to the very old leaflet.js version 1.34 only available through the internet archive. The current stable version is Leaflet 1.9.4, and version 2.0 is already in preparation (see: Leaflet 2.0.0-alpha).
Yesterday (August 16, 2025) the blog article Leaflet 2.0 Alpha released has been updated. It explains the new features in Leaflet.js 2.0. I assume that in the near future the R {leaflet} package will be updated.
Instead of the internet archive of the current offical documentation I will use in this book to documentation of the current latest stable version 1.9.4.
3.3 The Map Widget
3.3.1 Initializing options
The function leaflet::leaflet() returns a Leaflet map widget, which stores a list of objects that can be modified or updated later. The map widget can be initialized with certain parameters. This is achieved by populating the options argument as in the following example.
Code
# Set value for the minZoom and maxZoom settings.leaflet(options =leafletOptions(minZoom =0, maxZoom =18))
You can manipulate the attributes of the map widget using a series of methods.
leaflet::setView() sets the center of the map view and the zoom level; leaflet::fitBounds() fits the view into the rectangle [lng1, lat1] – [lng2, lat2]; leaflet::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.
Both leaflet::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 {maps} package:
the data frame returned from maps::map()
Simple features from the {sf} package:
leaflet::leaflet() is, additionally, back-compatible with {sp} SpatialDataFrames, although the use of these is discouraged for new users.
Important 3.2
The data argument is used to derive spatial data for functions that need it; for example, if data is a {sf} Simple Features data.frame, then calling leaflet::addPolygons() on that map widget will know to add the polygons from the geometry column.
For a normal matrix or data frame, any numeric column could potentially contain spatial data. So we resort to guessing based on column names:
latitude variable is guessed by looking for columns named lat or latitude (case-insensitive)
longitude variable is guessed by looking for lng, long, or longitude
You can always explicitly identify latitude/longitude columns by providing lng and lat arguments to the layer function.
A map layer may use a different data object to override the data provided in leaflet::leaflet().
R Code 3.3 : Overriding data provided with leaflet::leaflet() in another layer
Listing / Output 3.3: Overriding data provided with leaflet::leaflet() in another layer
Code
df=data.frame(Lat =1:10, Long =rnorm(10))leaflet::leaflet()|>leaflet::addCircles(data =df)glue::glue("------------------------------------------------------------------------")leaflet::leaflet()|>leaflet::addCircles(data =df, lat =~Long, lng =~Lat)
Graph 3.2: The data from the first leaflet call was reversed by the second layer on the second leaflet call
Graph 3.4: I succeeded with my first leaflet example using myRWB dataset. But the result is still ugly. I still have to learn about the many parameters to get better maps.
My first example worked. Although I have added two more lines than necessary the result is still ugly. There are so many options I have still to learn!
3.3.4 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).
R Code 3.5 : Formula Interface
Listing / Output 3.5: Arguments as R objects and the formula interface
Code
# preventing message 'Assuming "lng" and "lat" are longitude and latitude, respectively'df=data.frame( lat =rnorm(100), lng =rnorm(100), size =runif(100, 5, 20), color =sample(colors(), 100))m=leaflet::leaflet(df)|>leaflet::addTiles()m|>leaflet::addCircleMarkers(radius =~size, color =~color, fill =FALSE)glue::glue("------------------------------------------------------------------------")m|>leaflet::addCircleMarkers(radius =runif(100, 4, 10), color =c('red'))
Graph 3.5: Arguments as R objects and the formula interface
Graph 3.6: Arguments as R objects and the formula interface
Glossary Entries
term
definition
Choropleth
A choropleth map is a type of thematic map that uses shading or coloring to represent statistical data across predefined geographic regions. These regions can be political boundaries, such as states or countries, or natural divisions. Each area is colored based on the value of the variable being represented, typically using a gradient where darker shades indicate higher values and lighter shades indicate lower values. This visualization technique helps viewers quickly grasp patterns and trends within the dataset. It is important to note that choropleth maps can sometimes lead to misinterpretation due to the bias introduced by the size of the regions. Larger regions may appear to have more significance simply because of their size, even if their data values are the same as smaller regions. In this case use Cartograms.
CRS
A Coordinate Reference System (CRS) defines how locations on the Earth’s surface are represented in a two-dimensional plane. This is essential for accurate mapping and spatial analysis. CRSs are often defined using the PROJ.4 notation, which is a standard way to describe coordinate systems. CRSs can also be identified using EPSG codes, which are unique identifiers for different coordinate systems.
Mercator-projection
The Mercator projection is a conformal cylindrical map projection first presented by Flemish geographer and mapmaker Gerardus Mercator in 1569. It became the standard map projection for navigation in the 18th century due to its unique property of representing any course of constant bearing as a straight segment on the map. This feature made it invaluable for marine navigation, as sailors could plot a straight-line course on the map and maintain a constant compass heading to reach their destination. The projection is created by projecting the spherical Earth onto a cylinder that is tangent to the equator, then unrolling the cylinder into a flat plane. This process preserves angles and the shapes of small objects, making it conformal, but it significantly distorts the size of landmasses as latitude increases away from the equator. Consequently, regions near the poles, such as Greenland and Antarctica, appear much larger than they actually are relative to landmasses near the equator. For example, Africa is approximately 14 times larger than Greenland in reality, yet on a Mercator map, they appear similar in size. Despite its distortions, the Mercator projection remains widely used, particularly in internet web maps. The Web Mercator projection, a variant that models the Earth as a perfect sphere, is employed by major mapping services like Google Maps and OpenStreetMap for its computational efficiency and suitability for zooming and panning. While it is no longer the standard for commercial and educational world maps due to its unbalanced representation, it persists in digital mapping applications. The projection's continued use highlights the trade-off between preserving navigational accuracy and representing true landmass sizes, a fundamental challenge in cartography.
RWB
Reporters Without Borders (RWB), known by its French name Reporters sans frontières and acronym RSF, is an international non-profit and non-governmental organization headquartered in Paris, France, founded in 1985 in Montpellier by journalists Robert Ménard, Rémy Loury, Jacques Molénat, and Émilien Jubineau. It is dedicated to safeguarding the right to freedom of information and defends journalists and media personnel who are imprisoned, persecuted, or at risk for their work. The organization has consultative status at the United Nations, UNESCO, the Council of Europe, and the International Organisation of the Francophonie.
Lovelace, Robin, Jakub Nowosad, and Jannes Muenchow. 2025. Geocomputation With R. 2nd ed. Boca Raton, FL: Chapman & Hall/CRC.
Sievert, Carson. 2019. Interactive Web-Based Data Visualization with r, Plotly, and Shiny. https://plotly-r.com/.
I should get into the custom to document the writing dates for specific chapters. I have documented this now for this chapter directly unter the chapter heading.↩︎
# Learn Leaflet (1) {#sec-chap051}August 17-20, 2025```{r}#| label: setup#| results: hold#| include: falsebase::source(file ="R/helper.R")```:::::: {#obj-chap051}::::: my-objectives::: my-objectives-headerObjectives:::::: my-objectives-containerLearn the basics of {**leaflet**} using my `r glossary("RWB")` data as practicalexample::::::::::::::## Preliminary remarkAfter following [Making maps with R](https://r.geocompx.org/adv-map)(chapter 9 of the online book [Geocomputation withR](https://r.geocompx.org/)) and making my own research (see my notes in @sec-chap041) it turned out that[{**leaflet**}](https://rstudio.github.io/leaflet/index.html) /[leaflet.js](https://leafletjs.com/) is the most mature and widely usedinteractive mapping package in R interactive map drawing software.{**leaflet**} has twice more downloads than {**tmap**} which is as themoment the leading spatial geographic map tool. (See@lst-051-mapping-packages-downloads which contains a list of downloadsfor several map drawing packages.)::: {#nte-051-new-map-package-maps .callout-note}##### Added {**maps**} to @lst-051-mapping-packages-downloadsI just learned in the section @sec-051-data-object that {**maps**} isanother important package ranking with it download numbers in the secondplace!I added this package therefore to @lst-051-mapping-packages-downloads.The above paragraph is not correct anymore as {**maps**} has about 50%more downloads than {**leaflet**}.::::::::: my-r-code:::: my-r-code-header::: {#cnj-051-mapping-packages-downloads}: Overview of download numbers of map packages:::::::::: my-r-code-container```{r}#| label: mapping-packages-downloads#| lst-label: lst-051-mapping-packages-downloads#| lst-cap: Overview of download numbers of map packagesmy_pkgs_dl(pkgs =c("tmap", "plotly", "mapview","mapdeck","googleway","mapsf","mapmisc","leaflet","Rgooglemaps","ggmap","mapedit","ggiraph","maps" ),period ="last-month", days =30)```:::::::::Although {**leaflet**} has with about 3.000 downloads/day only about thehalf of the {**plotly**} downloads it is a specialized map drawingsoftware whereas {**plotly**} is a general interactive web graphicstool.> It’s worth noting that {**plotly**} aims to be a general purpose> visualization library, and thus, doesn’t aim to be the most fully> featured geo-spatial visualization toolkit. That said, there are> benefits to using {**plotly**}-based maps since the mapping APIs are> very similar to the rest of {**plotly**}, and you can leverage larger> {**plotly**} ecosystem (e.g., linking views client side … ). However,> if you run into limitations with {**plotly**}’s mapping functionality,> there is a very rich set of tools for interactive geospatial> visualization in R, including but not limited to: {**leaflet**},> {**mapview**}, {**mapedit**}, {**tmap**}, and {**mapdeck**} (Robin> Lovelace 2019). Quoted from chapter 4 of [@sievert2019].Another option to consider would be to use `ggplot2::geom_sf()` togetherwith- `plotly::ggplotly()` or `Hmisc::ggpltlyr()` (Converts a`ggplot2::ggplot()` object to a {**plotly**} object, in {**Hmisc**} variant removes extraneous text that ggplotly() puts in hover text)- `ggiraph::geom_sf_interactive()` (Make 'ggplot2' Graphics Interactive)- {**ggspatial**} (Spatial Data Framework for 'ggplot2')- {**geofacet**} (‘ggplot2’ Faceting Utilities for Geographical Data) This has the advantage that I am using with {**ggplot2**} known territory. But in this chapter I will focus on {**leaflet**}.:::::: my-resource:::: my-resource-header::: {#lem-051-leaflet}: Leaflet resources on the Internet:::::::::: my-resource-containerI am ignoring to list tutorials using Leaflet.js from scratch andcollect here only resources for learning the R {**leaflet**} package.Many tutorials cover some special actions like adding markers but myspecial focus at the moment is on `r glossary("choropleth")` maps.**Most important resources**- [An R Interface to Leaflet Maps](https://rstudio.github.io/leaflet/index.html): Official package documentation with a getting started page and several article covering a specific subject. I will start to learn the R leaflet package with this authoritative resource!- [Package {**leaflet**}](https://rstudio.r-universe.dev/leaflet/doc/manual.html): Official documentation in one page. Sorted not by function name but by short description. Helpful for looking up the name & syntax of a function for a specific problem. Last updated 2025-07-30.- [Leaflet.js](https://leafletjs.com/): Important for checking out the[API documentation of Leaflet](https://leafletjs.com/reference.html) occasionally when the meanings of certain parameters are not clear.- [Using arbitrary Leaflet JS plugins with Leaflet for R](https://gist.github.com/jcheng5/c084a59717f18e947a17955007dc5f92) by Joe Cheng- [Mapping applications](https://r.geocompx.org/adv-map#mapping-applications): Section of chapter 9 Making Maps with R of Geocomputation with R[@lovelace-2025].**Educational Online Courses**- [Interactive Maps with leaflet in R](https://app.datacamp.com/learn/courses/interactive-maps-with-leaflet-in-r): datacamp course, updated August 2024.**Additional resources**- [Mapping data in R](https://mapping-in-r.netlify.app/): Tutorial and[video](https://www.youtube.com/watch?v=w5U62wUki3E) by Lisa Lendway (Statistics and Data Science)- [Leaflet package in R](https://www.geeksforgeeks.org/r-language/leaflet-package-in-r/): geeksforgeeks, last updated 2025-07-23- [Interactive Maps with leaflet in R](https://r-graph-gallery.com/package/leaflet.html) and [Most basic background map with R and Leaflet](https://r-graph-gallery.com/179-show-a-map-with-leaflet-r.html): R Graph Gallery- [Interactive maps with leaflet in R](https://r-charts.com/spatial/interactive-maps-leaflet/): R Charts- [Leaflet](https://bookdown.org/nicohahn/making_maps_with_r5/docs/leaflet.html): Chapter of Making Maps with R [@hahn-2020]- [Interactive Maps with Leaflet](https://learn.r-journalism.com/en/mapping/leaflet_maps/leaflet/) and [Interactive Choropleth Maps](https://learn.r-journalism.com/en/mapping/census_maps/census-maps/): R for Journalists (includes for both part a video)- [Creating Interactive Spatial Maps in R Using Leaflet](https://earthdatascience.org/courses/earth-analytics/get-data-using-apis/leaflet-r/): Lesson 8 for the Earth Data Analytics Online Certificate by Earth Lab. [Data Scientist as Cartographer](https://library.virginia.edu/data/articles/data-scientist-as-cartographer-an-introduction-to-making-interactive-maps-in-r-with-leaflet): An Introduction to Making Interactive Maps in R with Leaflet by the Library of the University of Virgina. [An Introduction to R Leaflet](https://tomjenkins.netlify.app/tutorials/r-leaflet-introduction/): Tutorial by Tom Jenkins [Leaflet in R](https://www.jla-data.net/eng/leaflet-in-r-tips-and-tricks/) by Jindra Lacko.**Videos**- [Mapping in R with leaflet](https://www.youtube.com/watch?v=w5U62wUki3E) by Lisa Lendway. It has also a supporting [lesson text](https://mapping-in-r.netlify.app/). 13:49 min- [How to FULLY Customize Leaflet Maps using R programming](https://www.youtube.com/watch?v=U0aJeaCnMeE) by Felix Analytix. 12:31 min- [Create an Interactive Leaflet Map in R Studio](https://www.youtube.com/watch?v=M2x4eLh1Ltk) by Madhuraj PK. 8:07 min- [Introduction to Leaflet in R (R Tutorial For Beginners)](https://www.youtube.com/watch?v=F08PvG2c3P0) by GeoProgramming. 10:18 min:::::::::::: {#imp-051-second-trial .callout-important}##### This is already my second pass of the {**leaflet**} documentationI have already previously worked on the {**leaflet**}tutorials[^051-learn-leaflet-1].:::[^051-learn-leaflet-1]: I should get into the custom to document the writing dates for specific chapters. I have documented this now for this chapter directly unter the chapter heading.## Getting started### Basic usage:::::: my-procedure:::: my-procedure-header::: {#prp-051-basicprocedure-leaflet}: Four basic steps to produce a Leaflet map:::::::::: my-procedure-container1. Create a map widget by calling `leaflet::leaflet()`.2. Add layers (i.e., features) to the map by using layer functions (e.g., `leaflet::addTiles()`, `leaflet::addMarkers()`,`leaflet::addPolygons()`) to modify the map widget.3. Repeat step 2 as desired.4. Print the map widget to display it.:::::::::### Basic example:::::: my-r-code:::: my-r-code-header::: {#cnj-051-basic-example}: Basic R leaflet example:::::::::: my-r-code-container```{r}#| label: fig-051-basic-example#| lst-label: lst-051-basic-example#| lst-cap: "Basic R leaflet example"#| fig-cap: "A basic R leaflet example. Click at the marker to see what it indicates."library(leaflet)m <-leaflet() |># (1) Create the ma widget addTiles() |># (2) Add default OpenStreetMap map tilesaddMarkers(lng =174.768, # (3) Add another element to the maplat =-36.852,popup ="The birthplace of R")m # (4) Print the map```:::::::::### Next stepThe {**leaflet**} tutorial *highly* recommends to start with the article[The Map Widget](https://rstudio.github.io/leaflet/articles/widget.html)before exploring the rest of the site. It is the first article under themenu "Articles". It seems to me that the best way to learn leaflet is toproceed with the offered article in their sequence from top to thebottom of the menu.::: {#wrn-051-which-version .callout-warning}##### {**leaflet**} Documentation refers to leaflet.js version 1.34The links to the details leaflet.js documentation refers to the very old[leaflet.js version1.34](https://web.archive.org/web/20220512035219/https://leafletjs.com/reference-1.3.4.html)only available through the internet archive. The current stable versionis [Leaflet 1.9.4](https://leafletjs.com/reference.html), and version2.0 is already in preparation (see: [Leaflet2.0.0-alpha](https://leafletjs.com/reference-2.0.0.html)).Yesterday (August 16, 2025) the blog article [Leaflet 2.0 Alphareleased](https://leafletjs.com/2025/05/18/leaflet-2.0.0-alpha.html) hasbeen updated. It explains the new features in Leaflet.js 2.0. I assumethat in the near future the R {**leaflet**} package will be updated.**Instead of the internet archive of the current offical documentation Iwill use in this book to documentation of the current latest stableversion 1.9.4.**:::## The Map Widget### Initializing optionsThe function `leaflet::leaflet()` returns a Leaflet map widget, whichstores a list of objects that can be modified or updated later. The mapwidget can be initialized with certain parameters. This is achieved bypopulating the options argument as in the following example.```{r}#| label: demo-leaflet-options#| eval: false# Set value for the minZoom and maxZoom settings.leaflet(options =leafletOptions(minZoom =0, maxZoom =18))```The `leaflet::leafletOptions()` can be passed any option described inthe [leaflet referencedocument](https://leafletjs.com/reference#map-option).Using `leaflet::leafletOptions()`, you can set a custom`r glossary("CRS")` and have your map displayed in a non spherical`r glossary("Mercator-projection", "Mercator projection")` as describedin the article [Working with projections inLeaflet](https://rstudio.github.io/leaflet/articles/projections.html).### Map methodsYou can manipulate the attributes of the map widget using a series ofmethods.`leaflet::setView()` sets the center of the map view and the zoom level;`leaflet::fitBounds()` fits the view into the rectangle \[lng1, lat1\] –\[lng2, lat2\]; `leaflet::clearBounds()` clears the bound, so that theview will be automatically determined by the range of latitude/longitudedata in the map layers if provided.For more detailed information see the help file [Methods to manipulatethe mapwidget](https://rstudio.github.io/leaflet/reference/map-methods.html).The help file also refers to a detailed table listing [Methods formodifying mapstate](https://leafletjs.com/reference#map-methods-for-modifying-map-state).### The data object {#sec-051-data-object}Both `leaflet::leaflet()` and the map layer functions have an optionaldata parameter that is designed to receive spatial data in one ofseveral forms:- **From base R**: - `lng`/`lat` matrix - data frame with `lng`/`lat` columns- **From the {**maps**} package**: - the data frame returned from `maps::map()`- **Simple features from the {**sf**} package**:`leaflet::leaflet()` is, additionally, back-compatible with {**sp**}SpatialDataFrames, although the use of these is[discouraged](https://r-spatial.org/r/2023/04/10/evolution3.html) fornew users.::: {#imp-051-use-data-object .callout-important}The `data` argument is used to derive spatial data for functions thatneed it; for example, if data is a {**sf**} Simple Features data.frame,then calling `leaflet::addPolygons()` on that map widget will know toadd the polygons from the geometry column.:::For a normal matrix or data frame, any numeric column could potentiallycontain spatial data. So we resort to guessing based on column names:- **latitude variable** is guessed by looking for columns named `lat` or `latitude` (case-insensitive)- **longitude variable** is guessed by looking for `lng`, `long`, or`longitude`You can always explicitly identify latitude/longitude columns byproviding `lng` and `lat` arguments to the layer function.A map layer may use a different data object to override the dataprovided in `leaflet::leaflet()`.:::::: my-r-code:::: my-r-code-header::: {#cnj-051-overriding-data-in-map-layer}: Overriding data provided with `leaflet::leaflet()` in another layer:::::::::: my-r-code-container```{r}#| label: fig-051-overriding-data#| fig-cap: "The data from the first leaflet call was reversed by the second layer on the second leaflet call"#| lst-label: lst-051-overriding-data#| lst-cap: "Overriding data provided with `leaflet::leaflet()` in another layer" #| results: holddf =data.frame(Lat =1:10, Long =rnorm(10))leaflet::leaflet() |> leaflet::addCircles(data = df)glue::glue("------------------------------------------------------------------------")leaflet::leaflet() |> leaflet::addCircles(data = df, lat =~ Long, lng =~ Lat)```:::::::::In the next code chunk I am not following the tutorial but will use myown {**sf**} `r glossary("RWB")` dataset.:::::: my-r-code:::: my-r-code-header::: {#cnj-051-rwb-leaflet-example}: Using {sf} RWB dataset as my first leaflet example:::::::::: my-r-code-container```{r}#| label: fig-051-rwb-my-first-leaflet-example#| lst-label: lst-051-rwb-my-first-leaflet-example#| fig-cap: "I succeeded with my first leaflet example using myRWB dataset. But the result is still ugly. I still have to learn about the many parameters to get better maps."#| lst-cap: "Using {sf} RWB dataset as my first leaflet example"rwb_map_2025 <-readRDS(paste0(here::here(), "/data/chap041/rwb_map_2025.rds"))leaflet::leaflet() |> leaflet::addPolygons(data = rwb_map_2025) |> leaflet::addTiles(options = leaflet::tileOptions(noWrap =TRUE)) |> leaflet::clearBounds()```:::::::::::: {#nte-051-rwb-my-first-leaflet-example .callout-note}##### Evaluation of the result in @lst-051-rwb-my-first-leaflet-exampleMy first example worked. Although I have added two more lines thannecessary the result is still ugly. There are so many options I havestill to learn!:::### The Formula InterfaceThe arguments of all layer functions can take normal R objects, such asa numeric vector for the `lat` argument, or a character vector of colorsfor the `color` argument. They can also take a one-sided formula, inwhich case the formula will be evaluated using the `data` argument asthe environment. For example, `~ x` means the variable `x` in the dataobject, and you can write arbitrary expressions on the right-hand side,e.g., `~ sqrt(x + 1)`.:::::: my-r-code:::: my-r-code-header::: {#cnj-051-formula-interface}: Formula Interface:::::::::: my-r-code-container```{r}#| label: fig-051-formula-interface#| fig-cap: "Arguments as R objects and the formula interface"#| lst-label: lst-051-formula-interface#| lst-cap: "Arguments as R objects and the formula interface"#| results: hold#| warning: false# preventing message 'Assuming "lng" and "lat" are longitude and latitude, respectively'df =data.frame(lat =rnorm(100), lng =rnorm(100), size =runif(100, 5, 20),color =sample(colors(), 100))m = leaflet::leaflet(df) |> leaflet::addTiles()m |> leaflet::addCircleMarkers(radius =~size, color =~color, fill =FALSE)glue::glue("------------------------------------------------------------------------")m |> leaflet::addCircleMarkers(radius =runif(100, 4, 10), color =c('red'))```:::::::::## Glossary Entries {.unnumbered}```{r}#| label: glossary-table#| echo: falseglossary_table()```------------------------------------------------------------------------## Session Info {.unnumbered}::::: my-r-code::: my-r-code-headerSession Info:::::: my-r-code-container```{r}#| label: session-infoxfun::session_info()```::::::::