R Language Introduction to Geographical Maps Making Dynamic HTML Maps with Leaflet


Example

Leaflet is an open-source JavaScript library for making dynamic maps for the web. RStudio wrote R bindings for Leaflet, available through its leaflet package, built with htmlwidgets. Leaflet maps integrate well with the RMarkdown and Shiny ecosystems.

The interface is piped, using a leaflet() function to initialize a map and subsequent functions adding (or removing) map layers. Many kinds of layers are available, from markers with popups to polygons for creating choropleth maps. Variables in the data.frame passed to leaflet() are accessed via function-style ~ quotation.

To map the state.name and state.center datasets:

library(leaflet)

data.frame(state.name, state.center) %>% 
    leaflet() %>% 
    addProviderTiles('Stamen.Watercolor') %>% 
    addMarkers(lng = ~x, lat = ~y, 
               popup = ~state.name, 
               clusterOptions = markerClusterOptions())
screenshot of leaflet map (Screenshot; click for dynamic version.)