Interactive Maps with leaflet
The leaflet package brings interactive maps to R. It wraps the popular Leaflet JavaScript library through the htmlwidgets framework, letting you create zoomable, pannable maps directly from R. You can use these maps in RStudio, Shiny applications, and R Markdown documents.
This guide walks you through creating maps, adding markers with popups, and layering different data types.
Installing and Loading leaflet
Install leaflet from CRAN:
install.packages("leaflet")
library(leaflet)
The package depends on R 3.5.0 or later. It automatically loads htmltools for popup content and magrittr for the pipe operator.
Creating Your First Map
Start with the leaflet() function to initialize a map. By default, it shows a blank world view. Add tiles using addTiles() to display map imagery:
leaflet() %>%
addTiles()
This gives you an interactive map with zoom and pan controls. The map centers on the world by default.
Set a specific location and zoom level using setView():
leaflet() %>%
addTiles() %>%
setView(lng = -122.4194, lat = 37.7749, zoom = 12)
This centers the map on San Francisco with a zoom level of 12.
Adding Markers
The addMarkers() function places markers on the map. You can provide coordinates directly or use data from a data frame:
# Single marker
leaflet() %>%
addTiles() %>%
addMarkers(lng = -122.4194, lat = 37.7749, popup = "San Francisco")
When working with data frames, use the formula notation to specify column names:
# Multiple markers from data frame
df <- data.frame(
name = c("Tokyo", "London", "New York"),
lat = c(35.6762, 51.5074, 40.7128),
lng = c(139.6503, -0.1278, -74.0060)
)
leaflet(df) %>%
addTiles() %>%
addMarkers(~lng, ~lat, popup = ~name)
The ~lng and ~lat formulas tell leaflet which columns contain the coordinates.
Popups and Labels
Popups appear when users click a marker. Labels appear on hover by default. Use the popup and label arguments to add both:
leaflet(df) %>%
addTiles() %>%
addMarkers(
~lng, ~lat,
popup = ~paste0("<b>", name, "</b>"),
label = ~name
)
The htmlEscape() function from htmltools sanitizes text to prevent HTML injection:
library(htmltools)
leaflet(df) %>%
addTiles() %>%
addMarkers(
~lng, ~lat,
popup = ~htmlEscape(name)
)
For labels that are always visible, use labelOptions() with noHide = TRUE:
leaflet() %>%
addTiles() %>%
addMarkers(
lng = -122.4194, lat = 37.7749,
label = "Always visible label",
labelOptions = labelOptions(noHide = TRUE)
)
Customize label appearance with text size, color, and CSS:
leaflet() %>%
addTiles() %>%
addMarkers(
lng = -122.4194, lat = 37.7749,
label = "Styled label",
labelOptions = labelOptions(
noHide = TRUE,
textsize = "15px",
style = list("color" = "red", "font-weight" = "bold")
)
)
Tile Providers
The default OpenStreetMap tiles work, but leaflet supports many providers. The addProviderTiles() function loads different tile layers:
leaflet() %>%
addProviderTiles(providers$CartoDB.Positron) %>%
setView(lng = -122.4194, lat = 37.7749, zoom = 12)
Popular providers include CartoDB.Positron for a clean light theme, CartoDB.DarkMatter for dark mode, and Esri.WorldImagery for satellite imagery. The providers object contains dozens of tile options from various mapping services.
Switch between providers easily:
# Satellite view
leaflet() %>%
addProviderTiles(providers$Esri.WorldImagery) %>%
setView(lng = -122.4194, lat = 37.7749, zoom = 14)
Adding Shapes
Beyond markers, you can add circles, lines, and polygons:
# Circle
leaflet() %>%
addTiles() %>%
addCircles(lng = -122.4194, lat = 37.7749, radius = 500)
# Rectangle (polygon)
leaflet() %>%
addTiles() %>%
addRectangles(
lng1 = -122.43, lat1 = 37.78,
lng2 = -122.40, lat2 = 37.77,
popup = "Area popup"
)
Circles are useful for showing reach or coverage areas. Polygons draw arbitrary shapes on the map.
Customizing Markers
The default blue markers work, but you can customize icons and colors. Use addAwesomeMarkers() for additional icon options:
# Custom colored icons
library(leaflet.extras)
leaflet(df) %>%
addTiles() %>%
addAwesomeMarkers(
~lng, ~lat,
icon = awesomeIcons(
library = "fa",
icon = "star",
markerColor = "red",
iconColor = "white"
)
)
Available marker colors include red, blue, green, purple, orange, darkred, lightred, beige, darkblue, darkgreen, and more.
Marker Clustering
When displaying many markers, clustering improves performance and usability. The leaflet.extras package provides this feature:
install.packages("leaflet.extras")
library(leaflet.extras)
leaflet(df) %>%
addTiles() %>%
addMarkerClusterOptions()
This groups nearby markers into clusters that expand when clicked. Each cluster displays the number of markers it contains.
Conclusion
The leaflet package makes interactive mapping accessible from R. You can create maps with a few lines of code, add markers with popups, customize labels, switch tile providers, layer multiple shape types, and even cluster markers for better performance. The package integrates seamlessly with Shiny for building map-based applications.
For more advanced spatial visualization, explore the sf package for working with vector spatial data formats.
See Also
- Spatial Data with sf — Work with geographic vector data in R using simple features
- Data Wrangling with dplyr — Transform data before mapping it
- Reading and Writing CSV Files in R — Load location data from spreadsheets