Marco Sciaini

Interactive Mapping with Leaflet in R

20 Jun 2015

Introduction

Leaflet lets you create interactive maps right from the R console. Interactive panning and zooming allows for an explorative view on your pinpointed location. Leaflet provides a simple and fast way to host interactive maps online in R, requiring only 2 lines of code for a basic web map. It is developed by the RStudio team and has therefore a great integration in a workflow with shiny.

The basic usage looks like this:

  1. Create a map widget
  2. Add layers of your interest
  3. Render the map
  4. ... enjoy your beautiful map

1. First Steps

But, where to start? The first step will be the installation of leaflet:

We have to use devtools because leaflet is not yet on CRAN.

The creation of a basic map-widget is afterwards rather simple:

The function leaflet() creates a map widget. You can pass your data at this point with the data argument, or add it later on.

For the sake of simplicity, it is very handy to use the pipe operator %>% of the magrittr package (Ctl+Shift+M in R-Studio). Since most of the leaflet functions use the argument data as their first one, this approach makes your code a lot easier to read and you avoid nested bracketted commands. This way we can gradually add elements to our map, one-by-one.

… voilà, your interactive map-widget with the default OpenStreetMap tile layer.

1.2 Adding Data

There are now several ways to illustrate your data:

addControl | addTiles | addWMSTiles | addPopups | addMarkers | addCircleMarkers | addCircles | addPolylines | addRectangles | addPolygons | addGeoJSON |

With these commands you can add graphics elements and layers to your map. The package provides four options to pass data to the map-widget:

  1. Data from base R:
    • lat/long matrix
    • data.frame with lat/long columns
  2. Data from the sp package:
    • any of the spatial classes provided by sp
  3. Data from maps package:
    • any of the maps from the map database
  4. JSON format:
    • add your data in GeoJSON or TopoJSON format via jsonlite

1.2.1 Example

Let’s try adding a hiking trail, one that I plan to hopefully hike in the near future: The Pacific Coast Trail (PCT). The trail spans 2,650 miles (4,265 kilometers) from Mexico to Canada through California, Oregon, and Washington.

First download some data and prepare the layers we want to add:

Now we use the appropriate functions to display the layers on the map-widget:

1.4 Useful commands from other spatial R packages

2. Exporting your Web Widget

To my current knowledge there are three ways to export the map-widget from R:

2.1 Shiny

We can render the leaflet object with the following lines of code:

2.2 RStudio GUI

RStudio offers a "clickable" solution to export the map-widget:

Viewer -> Export -> Save as Web Page...

However, these option is only avaible for small layers. The trail of the PCT has over 99,000 vertices and the export fails with:

2.3 Rmarkdown

By embedding the leaflet object in a rmarkdown document, which will be rendered into a html:

Note that with self_contained: no you fix the pandoc conversion error from the RStudio GUI.

2.4 Update

I just found this nice funtion from the htmlwidgets package:

Seems to be the smoothest way to export the map-widget, which works even for very big datasets.

3. A closer look on addTile() and addLayersControl()

For me, one of the fascinating things about the leaflet package was the diverse range of available tiles. With addTile(urlTemplate = ...) the integration of any tile is straightforward and lets you compose beautiful maps. A good resource of available tiles can be found here:

... but wouldn't it be cool to stack your favorite tiles and chose between them in your map-widget? Of course it would and the guys from RStudio just implemented these with addLayersControl. The function is like the whole package very simple. You define two groups: i) the baseGroup and ii) the overlayGroup. Then you pass each individual layer with the parameter group into one of the two groups. For the baseGroups can only one group at a time be viewed and for the overlayGroups each layer can be individually checked or unchecked.

Conclusion

In my opinion the possibility to embed the map-widget in a Shiny application makes the leaflet package very useful for every kind of spatial analysis. With an app created by shiny in combination with leaflet we can let the user of the app control the parameters of the display of the map, as well as the parameters for any sort of statistical analyse or underlying model. For more details have a look at http://rstudio.github.io/leaflet/shiny.html.