Skip to main content
v2026.11,986 entries · CC-BY 4.0

Leaflet in R: Interactive Maps With the leaflet Package

Install the leaflet R package, build markers, choropleths and layer controls, and read the output, with commands from the official documentation.

Written and maintained by CASRAI Editorial Board

Published

On this page

The leaflet R package builds interactive web maps from R code: you pipe layers such as tiles, markers, polygons and legends onto a map object, and the result is an HTML widget you can view in RStudio, embed in R Markdown output or use in Shiny. It is the R interface to the Leaflet JavaScript library, installed from CRAN with install.packages('leaflet'). This page covers what it does in research work, the install and first-map steps from the package documentation, a sourced function-to-argument reference, how to read the output, common problems and the free alternatives that build on it.

What leaflet is used for in research

The package documentation describes leaflet as an R package that “makes it easy to create Leaflet maps from R.” In research practice that means spatial results can be inspected and shared as an interactive map instead of a static figure: sampling sites as markers with popups, regional rates as a colour-coded choropleth, or earthquake observations as sized circles. Because the map is an HTML widget, the same code that explores the data can also produce the figure that ships with a report.

Leaflet is a mapping package, not a statistics package. It draws geometry and attributes you already hold in a data frame or an sf object, so the analysis (modelling, aggregation, joins) happens elsewhere in your R workflow. If you are new to the language itself, start with what the R statistical programming language is.

leaflet versus leafletR

A separate package called leafletR also exists, and searches for “leaflet r” can return it. This page covers the leaflet package on CRAN, whose documentation lives at rstudio.github.io/leaflet. Check the package name in library() calls when you copy code from older tutorials.

Package facts from CRAN

The CRAN package page lists the details below (checked 2026-11-17). Version numbers change as the package is updated, so confirm them on CRAN before you pin a version in a project.

Item Value on the CRAN page
Version 2.2.3, published 2025-09-04
License MIT + file LICENSE
Depends R (>= 3.5)
Imports include htmlwidgets, htmltools, sf (>= 0.9-6), raster (>= 3.6.3), leaflet.providers (>= 2.0.0), RColorBrewer, scales, crosstalk
Documentation Reference manual (HTML and PDF), README and NEWS on CRAN; articles on the package website

How to install or access leaflet

The package website gives a single install command. Run it once in R, then load the package in each session.

install.packages('leaflet')
library(leaflet)

Because leaflet imports sf and raster, installing it also installs those packages if they are missing, which can take a few minutes on a fresh machine. If installing packages is new to you, how to install libraries in R walks through the general workflow, including what to do when an install fails.

How to make an interactive map with leaflet step by step

The steps below follow the examples on the leaflet website. Each layer function starts with add and is chained with the pipe, as the documentation shows with %>%.

1. Create the map and add the default tiles

  1. Load the package with library(leaflet).
  2. Create a map object with leaflet().
  3. Add the background with addTiles(), which uses the default OpenStreetMap tiles.
library(leaflet)
m <- leaflet() %>% addTiles()
m

2. Set the view and add a popup

The documentation’s first example centres the map with setView() and attaches a popup written in HTML:

m %>% setView(-93.65, 42.0285, zoom = 17)
m %>% addPopups(-93.65, 42.0285, 'Here is the <b>Department of Statistics</b>, ISU')

3. Plot points as markers

The markers article uses the quakes data set that ships with R. A formula such as ~long reads a column from the data passed to leaflet(). The popup argument opens on click, while label appears on hover or can be shown permanently.

leaflet(data = quakes[1:20,]) %>% addTiles() %>%
  addMarkers(~long, ~lat,
    popup = ~as.character(mag),
    label = ~as.character(mag))

If your columns are not called lat/lng (or similar), name them explicitly, as in addMarkers(lng = ~Longitude, lat = ~Latitude).

4. Colour circles by a category

addCircleMarkers() lets radius and colour depend on the data. The documentation maps a palette over a column and removes the outline with stroke = FALSE:

addCircleMarkers(radius = ~ifelse(type == "ship", 6, 10),
  color = ~pal(type), stroke = FALSE, fillOpacity = 0.5)

5. Cluster dense markers

For many points, addMarkers(clusterOptions = markerClusterOptions()) groups nearby markers into clusters. markerClusterOptions(freezeAtZoom = 5) freezes the clustering at a given zoom level.

6. Build a choropleth from an sf object

The choropleths article loads GeoJSON with the sf package into an sf data frame (called states in the example, with a density column), bins the values, colours polygons by bin and adds a legend:

bins <- c(0, 10, 20, 50, 100, 200, 500, 1000, Inf)
pal <- colorBin("YlOrRd", domain = states$density, bins = bins)

leaflet(states) %>% addTiles() %>%
  addPolygons(
    fillColor = ~pal(density),
    weight = 2, opacity = 1, color = "white",
    dashArray = "3", fillOpacity = 0.7,
    highlightOptions = highlightOptions()
  ) %>%
  addLegend(pal = pal, values = ~density, opacity = 0.7,
            title = NULL, position = "bottomright")

Choose bin breaks from your own data and domain knowledge; the breaks above are the documentation’s example values for US state population density, not a recommendation for other variables.

7. Switch the basemap

Replace addTiles() with addProviderTiles() and a provider name, for example addProviderTiles(providers$CartoDB.Positron) for a pale, low-clutter background that lets data layers stand out. The basemaps article also lists providers$Esri.NatGeoWorldMap, providers$OpenTopoMap and providers$Stadia.StamenToner. Tile layers can be stacked by passing options = providerTileOptions(opacity = 0.5), as in the article’s example of a semi-transparent providers$CartoDB.VoyagerOnlyLabels layer over providers$Esri.WorldImagery.

8. Let readers toggle layers

The show/hide article explains that the unit of showing and hiding is the group. You assign a layer to a group with the group argument, and add addLayersControl() with baseGroups (mutually exclusive basemaps) and overlayGroups (data layers that can be switched on and off). layersControlOptions(collapsed = FALSE) keeps the control expanded.

leaflet(quakes) %>%
  addTiles(group = "OSM (default)") %>%
  addProviderTiles(providers$CartoDB.Positron, group = "Positron (minimal)") %>%
  addCircles(~long, ~lat, ~10^mag/5, stroke = FALSE, group = "Quakes", fillColor = "tomato") %>%
  addLayersControl(
    baseGroups = c("OSM (default)", "Positron (minimal)"),
    overlayGroups = c("Quakes"),
    options = layersControlOptions(collapsed = FALSE)
  )

A data table below this guide maps each of these tasks to the function and arguments used in the documentation, with the source page for each.

How to read the output

A leaflet map is an interactive widget rather than an image. Drag to pan, scroll or use the zoom buttons to zoom, and click a marker to open its popup. Hover labels show only when the layer was given a label. Here is what each visible element tells you:

  • Tiles: the background map. With addTiles() these are OpenStreetMap tiles, and the footer credits “Maps © OpenStreetMap contributors” automatically. Keep that credit visible when you publish a map.
  • Markers and popups: one marker per row. The popup text is whatever expression you gave to popup, so a popup showing the wrong value usually means the wrong column was passed.
  • Choropleth fill: polygon colour follows the palette. With colorBin() every colour stands for a range of values, not a single value, so the legend bins are part of the result and belong in the figure caption.
  • Legend: addLegend() displays the palette from pal for the values you supply; a legend built from a different variable than the fill misleads readers.
  • Layers control: radio-style choices are base groups, check-box choices are overlay groups.

Attribution and tile providers in published maps

The basemaps article notes that some tile providers require registration and that keys are passed through providerTileOptions(). It also records that Stamen tiles moved to Stadia Maps in October 2023, and that published maps using them need a Stadia account. Before you submit a map to a journal or put it on a public site, check the terms of the provider you chose and keep its credit line in the figure.

Troubleshooting leaflet

The map shows no background

Maps start empty: leaflet() alone draws nothing. Add a tile layer with addTiles() or addProviderTiles(). If a provider requires registration, the tiles will not load without the key described in the basemaps article.

Markers do not appear or are in the wrong place

Markers need longitude and latitude. When the data columns have other names, pass them explicitly with lng = ~Longitude, lat = ~Latitude. Longitude comes first in the examples; swapping the two is a common cause of points landing in the wrong hemisphere.

A shape disappears after adding another

The show/hide article states that layer IDs must be unique: if you add a circle with a layer ID of “foo” and later add a different shape with the same ID, the original circle is removed. Likewise, a layer can belong to only zero or one group, so you cannot place one layer in two groups.

Installation fails on a missing dependency

The package imports sf and raster among others, and requires R 3.5 or later according to CRAN. Update R if your version is older, then reinstall; see how to install libraries in R.

A tutorial uses functions that do not exist

Older tutorials may refer to the separate leafletR package, or to Stamen providers whose hosting changed. Compare the code with the current articles and function reference on the package website.

Free alternatives to leaflet

Two CRAN packages build on leaflet rather than replace it. Both list leaflet among their imports on their CRAN pages (checked 2026-11-17), so they suit workflows where leaflet’s function-by-function control is more than you need. For charts rather than maps, see plotly in R and ggplots in R.

Package What CRAN says it does Relation to leaflet
mapview 2.11.4 Quickly and conveniently creates interactive visualisations of spatial data with or without background maps; attributes of features are queryable through pop-up windows. Imports leaflet (>= 2.0.0); requires R (>= 3.6.0).
tmap 4.4-1 Offers a flexible, layer-based approach to thematic maps such as choropleths and bubble maps. Imports leaflet (>= 2.0.2); requires R (>= 4.1).

Both packages are distributed through CRAN; check each package’s own license field before reuse.

Frequently asked questions

What is the leaflet package in R?

It is an R package that creates interactive Leaflet maps from R code. You install it from CRAN and build maps by chaining layer functions onto leaflet().

How do I install leaflet in R?

Run install.packages('leaflet'), then library(leaflet).

Does leaflet in R need an API key?

Not for the default OpenStreetMap tiles from addTiles(). The basemaps article states that some providers used through addProviderTiles() require registration, and keys are passed with providerTileOptions().

Can leaflet draw choropleth maps?

Yes. The choropleths article uses colorBin(), addPolygons() and addLegend() with polygon data read through the sf package.

What is the difference between leaflet and leafletR?

They are separate packages with similar names. This page and the rstudio.github.io/leaflet site describe the leaflet package.

Sources

Related: heatmap in R for gridded and matrix data.

Data: leaflet R package: task-to-function reference from the package documentation

Maps common mapping tasks to the leaflet function and the arguments used in the package website's own examples, compiled from the markers, choropleths, basemaps and show/hide articles.

leaflet R package: task-to-function reference from the package documentation
TaskFunctionArguments shown in the documentationDocumentation article
Add default OpenStreetMap backgroundaddTiles(none)Introduction
Centre the mapsetViewlng, lat, zoom (example: -93.65, 42.0285, zoom = 17)Introduction
Attach an HTML popup at a locationaddPopupslng, lat, popup textIntroduction
Plot points with click and hover textaddMarkers~long, ~lat, popup = ~as.character(mag), label = ~as.character(mag)Markers
Size and colour circles by dataaddCircleMarkersradius = ~ifelse(...), color = ~pal(type), stroke = FALSE, fillOpacity = 0.5Markers
Cluster dense pointsaddMarkersclusterOptions = markerClusterOptions(freezeAtZoom = 5)Markers
Colour polygons by valueaddPolygonsfillColor = ~pal(density), weight = 2, opacity = 1, color = "white", dashArray = "3", fillOpacity = 0.7Choropleths
Bin values into a palettecolorBinpalette name "YlOrRd", domain, binsChoropleths
Add a legendaddLegendpal, values, opacity = 0.7, title = NULL, position = "bottomright"Choropleths
Use a different basemapaddProviderTilesproviders$CartoDB.PositronUsing Basemaps
Stack semi-transparent tilesaddProviderTilesoptions = providerTileOptions(opacity = 0.5)Using Basemaps
Let readers toggle layersaddLayersControlbaseGroups, overlayGroups, options = layersControlOptions(collapsed = FALSE)Show/Hide Layers

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Leaflet in R: Interactive Maps With the leaflet Package

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →