9.10 Interactive Maps

tmap_mode("view") # or use tmap_leaflet()
## tmap mode set to interactive viewing
map_nz3
## stars object downsampled to 877 by 1140 cells. See tm_shape manual (argument raster.downsample)
elevation
0 to 500
500 to 1,000
1,000 to 1,500
1,500 to 2,000
2,000 to 2,500
2,500 to 3,000
3,000 to 3,500
Leaflet | Tiles © Esri — Esri, DeLorme, NAVTEQ
map_nz + tm_basemap(server = "OpenTopoMap")
Leaflet | Map data: © OpenStreetMap contributors, SRTM | Map style: © OpenTopoMap (CC-BY-SA)
world_coffee = left_join(world, coffee_data, by = "name_long")
facets = c("coffee_production_2016", "coffee_production_2017")
tm_shape(world_coffee) + tm_polygons(facets) + 
  tm_facets(nrow = 1, sync = TRUE)
coffee_production_2016
1 to 500
501 to 1,000
1,001 to 1,500
1,501 to 2,000
2,001 to 2,500
2,501 to 3,000
3,001 to 3,500
Missing
Leaflet | Tiles © Esri — Esri, DeLorme, NAVTEQ
coffee_production_2017
1 to 500
501 to 1,000
1,001 to 1,500
1,501 to 2,000
2,001 to 2,500
2,501 to 3,000
Missing
Leaflet | Tiles © Esri — Esri, DeLorme, NAVTEQ
# restore static plot default
tmap_mode("plot")
## tmap mode set to plotting

9.10.1 Mapview

mapview::mapview(nz)
nz
300 km
200 mi
Leaflet | © OpenStreetMap contributors © CARTO

Consider the following example where sf is used to intersect lines and polygons and then is visualized with mapview

Mapview example

9.10.2 Mapdeck

A unique feature of mapdeck is its provision of interactive ‘2.5d’ perspectives

Mapdeck example

9.10.3 Leaflet

leaflet which is the most mature and widely used interactive mapping package in R. leaflet provides a relatively low-level interface to the Leaflet JavaScript library. Here is the leaflet package in action, showing cycle hire points in London.

pal = colorNumeric("RdYlBu", domain = cycle_hire$nbikes)
leaflet(data = cycle_hire) |> 
  addProviderTiles(providers$CartoDB.Positron) |>
  addCircles(col = ~pal(nbikes), opacity = 0.9) |> 
  addPolygons(data = lnd, fill = FALSE) |> 
  addLegend(pal = pal, values = ~nbikes) |> 
  setView(lng = -0.1, 51.5, zoom = 12) |> 
  addMiniMap()

FIGURE 9.23: The leaflet package in action, showing cycle hire points in London.