Using Basemaps

Leaflet supports basemaps using map tiles, popularized by Google Maps and now used by nearly all interactive web maps.

Default (OpenStreetMap) Tiles

The easiest way to add tiles is by calling addTiles() with no arguments; by default, OpenStreetMap tiles are used.

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

Third-Party Tiles

Alternatively, many popular free third-party basemaps can be added using the addProviderTiles() function, which is implemented using the leaflet-providers plugin. See here for the complete set.

As a convenience, leaflet also provides a named list of all the third-party tile providers that are supported by the plugin. This enables you to use auto-completion feature of your favorite R IDE (like RStudio) and not have to remember or look up supported tile providers; just type providers$ and choose from one of the options. You can also use names(providers) to view all of the options.

m %>% addProviderTiles(providers$Stamen.Toner)
m %>% addProviderTiles(providers$CartoDB.Positron)
m %>% addProviderTiles(providers$Esri.NatGeoWorldMap)

Note that some tile set providers require you to register; see the project page for more information. You can pass access tokens/keys, and other options, to the tile provider by populating the options argument with the providerTileOptions() function.

Custom Tile URL Template

If you happen to have a custom map tile URL template to use, you can provide it as an argument to addTiles().

WMS Tiles

You can use addWMSTiles() to add WMS (Web Map Service) tiles. The map below shows the Base Reflectivity (a measure of the intensity of precipitation occurring) using the WMS from the Iowa Environmental Mesonet:

leaflet() %>% addTiles() %>% setView(-93.65, 42.0285, zoom = 4) %>%
    layers = "nexrad-n0r-900913",
    options = WMSTileOptions(format = "image/png", transparent = TRUE),
    attribution = "Weather data © 2012 IEM Nexrad"

Combining Tile Layers

You aren’t restricted to using a single basemap on a map; you can stack them by adding multiple tile layers. This generally only makes sense if the front tiles consist of semi transparent tiles, or have an adjusted opacity via the options argument.

m %>% addProviderTiles(providers$MtbMap) %>%
    options = providerTileOptions(opacity = 0.35)) %>%

The "leaflet" R package is copyright © 2014-2016 RStudio, Inc.
The Leaflet JavaScript library is © 2010–2016 Vladimir Agafonkin, 2010–2011 CloudMade.
Maps © OpenStreetMap contributors unless otherwise noted.

Fork me on GitHub