Appendix: Advanced Mapping Techniques with Leaflet

Introduction

In this appendix, we delve into advanced mapping techniques using the Leaflet package in R. Leaflet is a powerful library for creating interactive maps with extensive customization options. This section covers the basics of adding different types of base maps (tiles), integrating third-party map providers, and using various additional features such as WMS layers, mini maps, and custom JavaScript actions.

library(leaflet)

Introduction to Basemaps in Leaflet

Leaflet supports basemaps through the use of map tiles, which are small images that are stitched together to form a complete map. These tiles, popularized by Google Maps, are now used by almost all web-based interactive maps.

Default Tiles (OpenStreetMap)

The simplest way to add tiles is by using the addTiles() function without any arguments; by default, it utilizes OpenStreetMap tiles.

library(leaflet)
m <- leaflet() %>% setView(lng = -71.0589, lat = 42.3601, zoom = 12)
m %>% addTiles()

Third-Party Tiles

Leaflet supports numerous free and popular third-party basemaps through the addProviderTiles() function, implemented via the leaflet-providers plugin. These can easily be integrated into your maps.

Example with CartoDB Positron:

m %>% addProviderTiles(providers$CartoDB.Positron)

Example with Esri NatGeo World Map:

m %>% addProviderTiles(providers$Esri.NatGeoWorldMap)

Example with OpenTopoMap:

m %>% addProviderTiles(providers$OpenTopoMap)

Example with Stadia Stamen Toner:

m %>% addProviderTiles(providers$Stadia.StamenToner)

Note: Some tile providers may require registration. For more details, refer to the project page.

Custom Tile URL

For those with a custom map tile URL, you can use it as an argument in addTiles() to integrate your own basemaps.

WMS Tiles

Web Map Service (WMS) tiles can be added to your map, allowing for dynamic layers such as weather data. Below is an example using tiles from the Iowa Environmental Mesonet.

leaflet() %>%
  addTiles() %>%
  setView(-93.65, 42.0285, zoom = 4) %>%
  addWMSTiles(
    "http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
    layers = "nexrad-n0r-900913",
    options = WMSTileOptions(format = "image/png", transparent = TRUE),
    attribution = "Weather data © 2012 IEM Nexrad"
  )

Combining Tile Layers

Leaflet allows for the stacking of multiple tile layers, enabling complex map compositions.

m %>%
  addProviderTiles(
    providers$Esri.WorldImagery,
    options = providerTileOptions(opacity = 0.5)
  ) %>%
  addProviderTiles(providers$CartoDB.VoyagerOnlyLabels)

Additional Features

Leaflet comes with a variety of utility functions to enhance your maps with additional elements. These functions are highly customizable, making it easy to tailor your map to your specific needs.

Leaflet Measure Tool

Add measurement tools to your map using the addMeasure() function.

library(leaflet)
m <- leaflet() %>% addTiles()
m %>%
  fitBounds(-73.9, 40.75, -73.95, 40.8) %>%
  addMeasure()

Graticule (Grid)

You can add a graticule (grid) to the map with addGraticule(), which can be customized by interval and style.

library(leaflet)
m <- leaflet() %>% addTiles() %>% setView(0,0,2)
m %>% addGraticule(interval = 40, style = list(color = "#FF0000", weight = 1))

Terminator (Day/Night Indicator)

Visualize the day/night transition on the map using addTerminator().

library(leaflet)
leaflet() %>% addTiles() %>% addTerminator()

Mini Map

Enhance map navigation with a mini map using addMiniMap().

library(leaflet)
l <- leaflet() %>% setView(0,0,3)
l %>%
  addProviderTiles(providers$Esri.WorldStreetMap) %>%
  addMiniMap(
    tiles = providers$Esri.WorldStreetMap,
    toggleDisplay = TRUE)

EasyButton

Implement custom map controls with addEasyButton().

library(leaflet)
library(htmltools)
library(htmlwidgets)
leaflet() %>% addTiles() %>%
  addEasyButton(easyButton(
    icon="fa-globe", title="Zoom to Level 1",
    onClick=JS("function(btn, map){ map.setZoom(1); }"))) %>%
  addEasyButton(easyButton(
    icon="fa-crosshairs", title="Locate Me",
    onClick=JS("function(btn, map){ map.locate({setView: true}); }")))

Advanced Features: Custom JavaScript with htmlwidgets::onRender()

You can add custom JavaScript behavior to your Leaflet map using htmlwidgets::onRender().

l <- leaflet() %>% setView(0,0,3)
esri <- grep("^Esri", providers, value = TRUE)
for (provider in esri) {
  l <- l %>% addProviderTiles(provider, group = provider)
}
l %>%
  addLayersControl(baseGroups = names(esri),
    options = layersControlOptions(collapsed = FALSE)) %>%
  addMiniMap(tiles = esri[[1]], toggleDisplay = TRUE,
    position = "bottomleft") %>%
  htmlwidgets::onRender("
    function(el, x) {
      var myMap = this;
      myMap.on('baselayerchange',
        function (e) {
          myMap.minimap.changeLayer(L.tileLayer.provider(e.name));
        })
    }")

Conclusion

In this chapter, we explored various methods for integrating basemaps into Leaflet maps, including the use of default tiles, third-party providers, custom URLs, and WMS tiles. Each technique offers unique advantages depending on the application and user needs.