Aug 11, 2015

Leaflet is a JavaScript library that has become quite popular for creating interactive maps. One way to create a map using the Leaflet JS library is to include the Leaflet JS and CSS files in the head of a web page and then set up the map in the body of the html page, as shown in the Leaflet Quick Start Guide.

An alternative way is to create the web map in the R environment using an R package called leaflet, developed by the guys from RStudio, which allows controlling and integrating Leaflet maps in R. In this post I show how to read a vector map in shapefile format and how to create a leaflet web map customizing the way the vector map is displayed. I will also show how to add a legend, a layers control and popups for displaying attribute data. I recommend to use the RStudio IDE for the purpose of this tutorial.

First we need to install the leaflet package in R entering the following command line in the R console:


The next step is to read into R the maps we want to display in our web map. For reading a shapefile, there are a number of functions included in different R packages (see rgdal, maptools, shapefiles, and others). I’m going to use the raster package, so we need to install it first:


Now let’s load the two packages:


For this example I am going to import in R a polygon shapefile enclosing the study area of one of my projects. The projection of this map is defined in geographic coordinates (latitude/longitude). Let’s use the shapefile function from the raster package to read the file:

llanos <- shapefile("C:/my_dir/llanos.shp")

In this case the file has been read into R as an SpatialPolygonsDataFrame object called llanos. Now we are going to create the leaflet map using this object for the data argument in the leaflet function. We can do that in just one line of code concatenating several commands with the forward pipe operator %>%. First we create a Leaflet map widget (with the leaflet command) and then add a tile layer (with addTiles), the vector map as polygon (addPolygons) and a legend (addLegend).

leaflet(data = llanos) %>% addTiles() %>% addProviderTiles(providers$OpenStreetMap) %>% 
  addPolygons(fill = FALSE, stroke = TRUE, color = "#03F") %>% addLegend("bottomright", colors = "#03F", labels = "Llanos ecoregion")

The fill, stroke and color arguments allow customizing whether to fill the polygon with color, whether to draw the border of the polygon, and the border color, respectively. For the addLegend command, we define the position, colors and labels of the legend. If you are working in RStudio, you should see your map displayed in the ‘Viewer’ tab when you hit enter:

Web map with leaflet

Leaflet displays OpenStreetMap (OSM) tiles by default but you can use any basemap provider (e.g., MapQuest Open, MapBox, Bing Maps, etc.) as long as you conform to its terms of use. You can see the help page for the addTiles function in R, if needed, entering ?addTiles in the R console.

We can display more than one map at a time with leaflet. For this example I am going to overlay another polygon feature that shows the Landsat scenes that cover my study area based on the WRS2 descending grid. Let’s read this second shapefile:

wrs2 <- shapefile("C:/my_dir/wrs2_desc.shp")

As before, we create the Leaflet map widget, add the OSM tiles and add the polygons. For adding layers controls, we need to provide the name of the group the newly created layers should belong to. For example, I will define “Study area” as the group for the llanos layer, and the “Landsat scenes” group for the wrs2 layer. For popups, the popup argument in the addPolygons function is used to display attribute data from the vector map. In this case, I am using a column called ‘PATH_ROW’ that indicates the path and row of the corresponding Landsat scene.

For the legend, we add pairs of values for the colors and labels arguments for the corresponding values of the two map layers. Finally, the addLayersControl function allows the addition of user interface controls to switch the layers on and off. We have to enter the name of the group each layer map belong to in the overlayGroups argument and then we define whether we want the layers control to be collapsed or not, using the options argument. The complete code snippet can be seen below:

leaflet() %>% addTiles() %>% addProviderTiles(providers$OpenStreetMap) %>%   
  addPolygons(data = llanos, fill = FALSE, stroke = TRUE, color = "#03F", group = "Study area") %>% 
  addPolygons(data = wrs2, fill = TRUE, stroke = TRUE, color = "#f93", 
              popup = paste0("Scene: ", as.character(wrs2$PATH_ROW)), group = "Landsat scenes") %>% 
  # add a legend
  addLegend("bottomright", colors = c("#03F", "#f93"), labels = c("Study area", "Landsat scenes (path - row)")) %>%   
  # add layers control
    overlayGroups = c("Study area", "Landsat scenes"),
    options = layersControlOptions(collapsed = FALSE)

Finally export the map as an html page. In the ‘Viewer’ tab in RStudio, click the ‘Export’ button and then click ‘Save as Web page…’. Then you just need to upload your output html page to your website to make your map available online. You can see an example of a map created with leaflet in this link.

Once uploaded, you can also embed your map in another web page inserting a code snippet like the one below wherever you want to display it:

<iframe width="700" height="500" src=""></iframe>

Now you have a fancy web map with legend, layers controls and popups:

That’s it. Congratulations for finishing this first tutorial!

Share this post:   

Subscribe to my blog and get the '50 best QGIS plugins' ebook completely free!