Interactive Maps with leaflet
Render interactive web maps with markers, popups, and tile layers.
Interactive Maps with leaflet is a free R Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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'
)
map2addMarkers with Popups
addMarkers(lng, lat, popup) adds pin markers to the map. The popup argument accepts HTML strings, so you can include bold text, links, or images. The label argument shows text on hover without a click.
library(leaflet)
cities <- data.frame(
name = c('New York', 'Los Angeles', 'Chicago'),
lon = c(-74.006, -118.244, -87.629),
lat = c( 40.713, 34.052, 41.878),
pop = c(8336817, 3979576, 2693976)
)
leaflet(cities) |>
addTiles() |>
addMarkers(
lng = ~lon,
lat = ~lat,
popup = ~paste0(
'<b>', name, '</b><br>',
'Population: ', format(pop, big.mark = ',')
),
label = ~name
)addCircleMarkers
addCircleMarkers() renders circles whose size is fixed in screen pixels (unlike addCircles() which scales with zoom). They are ideal for representing proportional symbols — map the radius to a data variable.
library(leaflet)
cities <- data.frame(
name = c('New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix'),
lon = c(-74.006, -118.244, -87.629, -95.369, -112.074),
lat = c( 40.713, 34.052, 41.878, 29.760, 33.449),
pop = c(8336817, 3979576, 2693976, 2304580, 1608139)
)
leaflet(cities) |>
addProviderTiles(providers$CartoDB.Positron) |>
addCircleMarkers(
lng = ~lon,
lat = ~lat,
radius = ~sqrt(pop / 50000),
color = 'steelblue',
fill = TRUE,
fillOpacity = 0.6,
popup = ~paste0(name, ': ', format(pop, big.mark = ','))
)addPolygons: Choropleth Maps
addPolygons() renders polygon geometries directly from an sf object. Fill colour can be mapped to a data column using colorNumeric() or colorBin() palette functions. A highlight option adds hover effects.
library(leaflet)
library(sf)
nc <- st_transform(
read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)
# Colour palette based on birth count
pal <- colorNumeric('YlOrRd', domain = nc$BIR74)
leaflet(nc) |>
addProviderTiles(providers$CartoDB.Positron) |>
addPolygons(
fillColor = ~pal(BIR74),
fillOpacity = 0.7,
color = 'white',
weight = 1,
popup = ~paste0('<b>', NAME, '</b><br>Births 1974: ', BIR74),
highlight = highlightOptions(
weight = 3,
color = '#333',
bringToFront = TRUE
)
) |>
addLegend('bottomright', pal = pal, values = ~BIR74, title = 'Births 1974')setView and fitBounds
setView(lng, lat, zoom) centres the map on a fixed location and zoom level. fitBounds(lng1, lat1, lng2, lat2) automatically zooms to fit a geographic bounding box, which is useful when you don't know the data's extent in advance.
library(leaflet)
library(sf)
nc <- st_transform(
read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)
bbox <- st_bbox(nc)
# fitBounds: auto-zoom to data extent
leaflet() |>
addTiles() |>
fitBounds(
lng1 = bbox['xmin'], lat1 = bbox['ymin'],
lng2 = bbox['xmax'], lat2 = bbox['ymax']
) |>
addPolygons(
data = nc,
fillColor = 'lightblue',
fillOpacity = 0.4,
color = 'steelblue',
weight = 1
)addLayersControl: Toggle Layers
addLayersControl() adds a radio/checkbox control to toggle base maps and overlay layers on and off. Use baseGroups for mutually exclusive tile layers and overlayGroups for independently toggleable data layers.
library(leaflet)
library(sf)
nc <- st_transform(
read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)
high_birth <- nc[nc$BIR74 > 3000, ]
low_birth <- nc[nc$BIR74 <= 3000, ]
leaflet() |>
addProviderTiles(providers$CartoDB.Positron, group = 'Light') |>
addProviderTiles(providers$Esri.WorldImagery, group = 'Satellite') |>
addPolygons(data = high_birth, color = 'red', group = 'High Births (>3000)') |>
addPolygons(data = low_birth, color = 'blue', group = 'Low Births (<=3000)') |>
addLayersControl(
baseGroups = c('Light', 'Satellite'),
overlayGroups = c('High Births (>3000)', 'Low Births (<=3000)'),
options = layersControlOptions(collapsed = FALSE)
)addPopups and addLegend
addPopups() adds persistent (always-visible) popup boxes. addLegend() creates a map legend linked to a colour palette. Both support HTML content and are fully customisable with CSS classes.
library(leaflet)
leaflet() |>
addTiles() |>
setView(-79.0, 35.5, zoom = 7) |>
addPopups(
lng = -78.639,
lat = 35.779,
popup = '<b>Raleigh</b><br>State Capital of NC'
) |>
addLegend(
position = 'bottomleft',
colors = c('red', 'blue', 'green'),
labels = c('High', 'Medium', 'Low'),
title = 'Risk Level',
opacity = 0.8
)Colour Palettes: colorNumeric and colorBin
The colorNumeric(), colorBin(), colorQuantile(), and colorFactor() functions create palette functions that map data values to hex colours. Pass the result to fillColor and the same palette to addLegend().
library(leaflet)
library(sf)
nc <- st_transform(
read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)
# Continuous palette
pal_num <- colorNumeric('Blues', domain = nc$BIR74)
# Binned palette (5 equal bins)
pal_bin <- colorBin('RdYlGn', domain = nc$BIR74, bins = 5)
# Quantile palette (equal number of features per class)
pal_qtl <- colorQuantile('YlOrRd', domain = nc$BIR74, n = 4)
# Use binned palette
leaflet(nc) |>
addTiles() |>
addPolygons(
fillColor = ~pal_bin(BIR74),
fillOpacity = 0.7, weight = 1, color = 'white'
) |>
addLegend('bottomright', pal = pal_bin, values = ~BIR74,
title = 'Births 1974 (5 bins)')leafletProxy: Updating Maps in Shiny
leafletProxy('mapId') updates an existing leaflet map in a Shiny app without re-rendering the whole map from scratch. Use it with clearMarkers(), clearShapes(), or addMarkers() to efficiently respond to user input.
library(shiny)
library(leaflet)
# Minimal Shiny app with leafletProxy
ui <- fluidPage(
selectInput('colour', 'Marker colour:', choices = c('red', 'blue', 'green')),
leafletOutput('map')
)
server <- function(input, output, session) {
output$map <- renderLeaflet({
leaflet() |> addTiles() |>
setView(-79.0, 35.5, zoom = 7)
})
observeEvent(input$colour, {
leafletProxy('map') |>
clearMarkers() |>
addCircleMarkers(
lng = -78.639, lat = 35.779,
color = input$colour,
label = paste('Raleigh -', input$colour)
)
})
}
# shinyApp(ui, server) # uncomment to runFull Interactive Choropleth
Here is a production-quality choropleth combining all key features: provider tiles, polygon fill, hover highlights, dynamic popups, a colour legend, and layer controls — all in under 25 lines.
library(leaflet)
library(sf)
nc <- st_transform(
read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)
pal <- colorQuantile('YlOrRd', domain = nc$SID74, n = 5)
leaflet(nc) |>
addProviderTiles(providers$CartoDB.Positron) |>
addPolygons(
fillColor = ~pal(SID74),
fillOpacity = 0.75,
color = 'white',
weight = 0.5,
popup = ~paste0('<b>', NAME, '</b><br>SIDS 1974: ', SID74),
highlight = highlightOptions(
weight = 2, color = '#555', bringToFront = TRUE
)
) |>
addLegend(
position = 'bottomright',
pal = pal, values = ~SID74,
title = 'SIDS Deaths 1974<br>(Quintiles)'
) |>
addControl('<b>NC SIDS Data 1974</b>', position = 'topright')Quick Check
In a Shiny app, you want to update marker positions on an existing leaflet map when the user changes a dropdown — without re-rendering the entire map. Which function should you use?
Recap: leaflet Package
Key takeaways:
leaflet() |> addTiles()creates an interactive map with OpenStreetMap tilesaddProviderTiles(providers$switches to other tile providers) addMarkers()/addCircleMarkers()for point data; usepopupandlabeladdPolygons(fillColor = ~pal(col))for choropleth mapscolorNumeric(),colorBin(),colorQuantile()create palette functionsaddLegend()pairs with palette functions;addLayersControl()toggles layersleafletProxy()for efficient Shiny map updatesfitBounds()auto-zooms to data extent
library(leaflet)
# Three-line interactive map
leaflet() |>
addProviderTiles(providers$CartoDB.Positron) |>
addCircleMarkers(lng = c(-74, -118, -88), lat = c(41, 34, 42),
label = c('NYC', 'LA', 'Chicago'), color = 'steelblue')Frequently asked questions
Is the “Interactive Maps with leaflet” lesson free?
Yes — the full text of “Interactive Maps with leaflet” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.
What will I learn in “Interactive Maps with leaflet”?
Render interactive web maps with markers, popups, and tile layers. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start R Academy?
No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Interactive Maps with leaflet” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this R Academy lesson?
Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Simple Features with the sf Package
- Coordinate Reference Systems and Projections
- Spatial Joins and Operations
- Interactive Maps with leaflet