Interactive Maps with leaflet
Render interactive web maps with markers, popups, and tile layers.
Introduction to leaflet
The leaflet package wraps the Leaflet.js library to create interactive, zoomable web maps directly from R. Maps are HTML widgets that render in RStudio's Viewer, R Markdown, and Shiny apps without any JavaScript knowledge.
library(leaflet)
# Minimal leaflet map: tiles + one marker
leaflet() |>
addTiles() |> # OpenStreetMap base layer
setView(
lng = -74.006,
lat = 40.713,
zoom = 12
) |>
addMarkers(
lng = -74.006,
lat = 40.713,
popup = '<b>New York City</b>'
)addTiles: Base Map Layers
addTiles() adds the default OpenStreetMap tile layer. Use addProviderTiles(providers$ to switch to satellite imagery, CartoDB, Esri, Stamen, or any other tile provider. Layer names are in the built-in providers list.
library(leaflet)
# Default OpenStreetMap
map1 <- leaflet() |> addTiles()
# CartoDB light theme (great for data overlay)
map2 <- leaflet() |>
addProviderTiles(providers$CartoDB.Positron)
# Satellite imagery
map3 <- leaflet() |>
addProviderTiles(providers$Esri.WorldImagery)
# Custom tile URL
custom <- leaflet() |>
addTiles(
urlTemplate = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
attribution = '(c) OpenStreetMap contributors'
)
map2All lessons in this course
- Simple Features with the sf Package
- Coordinate Reference Systems and Projections
- Spatial Joins and Operations
- Interactive Maps with leaflet