Interactive maps with Leaflet


  1. Create interactive web maps using Leaflet and the leaflet R package.
  2. Change base maps
  3. Symbolize and display point and polygon data
  4. Configure pop-ups
  5. Add layer lists and legends
  6. Render a web map to HTML


Leaflet is an free and open-source JavaScript library and Application Programming Interface (API) for developing interactive web maps. It is very powerful, and offers a free alternative to propreitary web mapping software, such as ArcGIS Online and the ArcGIS API for JavaScript. It is used by many organizations including NPR, The Washington Post, Facebook, GitHub, USA Today, and the European Commission. Here is a link to the official Leaflet webpage.

Since Leaflet is meant to be used in the web development environment, it makes use of JavaScript, the dominant client-side programming language on the web. So, to use it effectively you need to have some understanding of JavaScript. It also doesn’t hurt to have knowledge of Hypertext Markup Language (HTML) and Cascading Style Sheets (CSS). So, there is a bit of a learning curve. Fortunately, the leaflet package allows for the use of Leaflet without the need to learn JavaScript. Interactive web maps can be ceated using R code then rendered to an HTML webpage. Since this course focuses on R, I will demonstrate using Leaflet through the associated R package. If you have an interest in web development, I would recommend learning some HTML, CSS, and JavaScript; howver, that is outside the scope of this course.

We will use a variety of packages in this module. If you don’t have these packages installed yet, you will need to do so before proceeding.

If you would like to install a development version of the leaflet package, you can do so using GitHub as demosntrated in the next code block.

In this demonstration, I will produce an interactive web map to visualize data summarized by county for the high plains states in the United States. The elevation, temperature, and precipitation data were extacted from raster grids provided by the PRISM Climate Group at Oregon State University. The elevation data are provided in feet, the temperature data represent 30-year annual normal mean temperature in Celsius, and the precipitation data represent 30-year annual normal precipitation in inches. The original raster grids have a resolution of 4 by 4 kilometers and can be obtained here. I also summarized percent forest (“per_for”") from the 2011 National Land Cover Database (NLCD). NLCD data can be obtained from the Multi-Resolution Land Characteristics Consortium (MRLC).

I am reading in the spatial data using the sf package.

Generally, web maps are generated using the WGS84 Web Mercator projection. So, data that will be used in a web map should be transformed to that projection. Or, they could be referenced to the WGS84 geographic datum. I have chosen to use the WGS84 Web Mercator projection, as defined by the European Petroleum Survey Group code 4326. st_tranform() is used to make the transformation. I then change the column names to make them more interpretable.

The cities point data contains a ordinal field representing different population range categories as follows:

  • 5: 2,500 to 9,999,
  • 6: 10,000 to 49,999
  • 7: 50,000 to 99,999
  • 8: 100,000 to 499,999
  • 9: 500,000 to 999,999

In order to display them separately, I split the data into new objects using the filter() function from dplyr after converting the data to a factor and printing the levels.

Base maps and Extents

Generally, you start designing a web map by defining a base map and default extent and zoom level. In the first example, I am simply creating a map with the default base map, extent, and zoom level by initializing the map with the leaflet() function then adding the base map using addTiles(). Raster Tile Layers represent picture of images or raw data as opposed to the original geospatial data files. They are stored as tiles that change based on the zoom level. Most base maps are stored as Raster Tile Layers.

In the example above, we did not explicitly state the desired extent and zoom level and by default the map loaded to a global extent. The setView() function is used to define the extent using latitude and longitude coordinates. The zoom level is then defined. Larger numbers indicate more zoomed in. A zoom level of 1 indicates a global extent. Take some time to change the coordinates and zoom level to see how this impacts the map. Note that positive values indicate north latitude or east longitude while negative values indicate south latitude or west longitude.

It is also possible to limit the user’s ability to zoom and pan using leafletOptions(). In the next code block I am defining a default extent and a default zoom level. Using minZoom and maxZoom I limit the allowed zoom levels. Setting dragging to FALSE will not allow the user to pan the map.

We will not use these options to prodcue our maps; however, I wanted to demo them, as this can be useful in many situations.

Ther are many base maps available other than the default OpenStreetMap base map. To print a list of available base maps, you can use the argument shown below. I have had issues in the past getting all of these layers to work depending on the computer and/or browser I am using. Unfortunately, I have not found a workaround for this issue. So, if you cannot get a base map to work, simply use a different one.

  [1] "OpenStreetMap"                      
  [2] "OpenStreetMap.Mapnik"               
  [3] "OpenStreetMap.BlackAndWhite"        
  [4] "OpenStreetMap.DE"                   
  [5] "OpenStreetMap.CH"                   
  [6] "OpenStreetMap.France"               
  [7] "OpenStreetMap.HOT"                  
  [8] "OpenStreetMap.BZH"                  
  [9] "OpenInfraMap"                       
 [10] "OpenInfraMap.Power"                 
 [11] "OpenInfraMap.Telecom"               
 [12] "OpenInfraMap.Petroleum"             
 [13] "OpenInfraMap.Water"                 
 [14] "OpenSeaMap"                         
 [15] "OpenPtMap"                          
 [16] "OpenTopoMap"                        
 [17] "OpenRailwayMap"                     
 [18] "OpenFireMap"                        
 [19] "SafeCast"                           
 [20] "Thunderforest"                      
 [21] "Thunderforest.OpenCycleMap"         
 [22] "Thunderforest.Transport"            
 [23] "Thunderforest.TransportDark"        
 [24] "Thunderforest.SpinalMap"            
 [25] "Thunderforest.Landscape"            
 [26] "Thunderforest.Outdoors"             
 [27] "Thunderforest.Pioneer"              
 [28] "OpenMapSurfer"                      
 [29] "OpenMapSurfer.Roads"                
 [30] "OpenMapSurfer.AdminBounds"          
 [31] "OpenMapSurfer.Grayscale"            
 [32] "Hydda"                              
 [33] "Hydda.Full"                         
 [34] "Hydda.Base"                         
 [35] "Hydda.RoadsAndLabels"               
 [36] "MapBox"                             
 [37] "Stamen"                             
 [38] "Stamen.Toner"                       
 [39] "Stamen.TonerBackground"             
 [40] "Stamen.TonerHybrid"                 
 [41] "Stamen.TonerLines"                  
 [42] "Stamen.TonerLabels"                 
 [43] "Stamen.TonerLite"                   
 [44] "Stamen.Watercolor"                  
 [45] "Stamen.Terrain"                     
 [46] "Stamen.TerrainBackground"           
 [47] "Stamen.TopOSMRelief"                
 [48] "Stamen.TopOSMFeatures"              
 [49] "Esri"                               
 [50] "Esri.WorldStreetMap"                
 [51] "Esri.DeLorme"                       
 [52] "Esri.WorldTopoMap"                  
 [53] "Esri.WorldImagery"                  
 [54] "Esri.WorldTerrain"                  
 [55] "Esri.WorldShadedRelief"             
 [56] "Esri.WorldPhysical"                 
 [57] "Esri.OceanBasemap"                  
 [58] "Esri.NatGeoWorldMap"                
 [59] "Esri.WorldGrayCanvas"               
 [60] "OpenWeatherMap"                     
 [61] "OpenWeatherMap.Clouds"              
 [62] "OpenWeatherMap.CloudsClassic"       
 [63] "OpenWeatherMap.Precipitation"       
 [64] "OpenWeatherMap.PrecipitationClassic"
 [65] "OpenWeatherMap.Rain"                
 [66] "OpenWeatherMap.RainClassic"         
 [67] "OpenWeatherMap.Pressure"            
 [68] "OpenWeatherMap.PressureContour"     
 [69] "OpenWeatherMap.Wind"                
 [70] "OpenWeatherMap.Temperature"         
 [71] "OpenWeatherMap.Snow"                
 [72] "HERE"                               
 [73] "HERE.normalDay"                     
 [74] "HERE.normalDayCustom"               
 [75] "HERE.normalDayGrey"                 
 [76] "HERE.normalDayMobile"               
 [77] "HERE.normalDayGreyMobile"           
 [78] "HERE.normalDayTransit"              
 [79] "HERE.normalDayTransitMobile"        
 [80] "HERE.normalNight"                   
 [81] "HERE.normalNightMobile"             
 [82] "HERE.normalNightGrey"               
 [83] "HERE.normalNightGreyMobile"         
 [84] "HERE.basicMap"                      
 [85] "HERE.mapLabels"                     
 [86] "HERE.trafficFlow"                   
 [87] "HERE.carnavDayGrey"                 
 [88] "HERE.hybridDay"                     
 [89] "HERE.hybridDayMobile"               
 [90] "HERE.pedestrianDay"                 
 [91] "HERE.pedestrianNight"               
 [92] "HERE.satelliteDay"                  
 [93] "HERE.terrainDay"                    
 [94] "HERE.terrainDayMobile"              
 [95] "FreeMapSK"                          
 [96] "MtbMap"                             
 [97] "CartoDB"                            
 [98] "CartoDB.Positron"                   
 [99] "CartoDB.PositronNoLabels"           
[100] "CartoDB.PositronOnlyLabels"         
[101] "CartoDB.DarkMatter"                 
[102] "CartoDB.DarkMatterNoLabels"         
[103] "CartoDB.DarkMatterOnlyLabels"       
[104] "HikeBike"                           
[105] "HikeBike.HikeBike"                  
[106] "HikeBike.HillShading"               
[107] "BasemapAT"                          
[108] "BasemapAT.basemap"                  
[109] "BasemapAT.grau"                     
[110] "BasemapAT.overlay"                  
[111] "BasemapAT.highdpi"                  
[112] "BasemapAT.orthofoto"                
[113] "nlmaps"                             
[114] "nlmaps.standaard"                   
[115] "nlmaps.pastel"                      
[116] "nlmaps.grijs"                       
[117] "nlmaps.luchtfoto"                   
[118] "NASAGIBS"                           
[119] "NASAGIBS.ModisTerraTrueColorCR"     
[120] "NASAGIBS.ModisTerraBands367CR"      
[121] "NASAGIBS.ViirsEarthAtNight2012"     
[122] "NASAGIBS.ModisTerraLSTDay"          
[123] "NASAGIBS.ModisTerraSnowCover"       
[124] "NASAGIBS.ModisTerraAOD"             
[125] "NASAGIBS.ModisTerraChlorophyll"     
[126] "NLS"                                
[127] "JusticeMap"                         
[128] "JusticeMap.income"                  
[129] "JusticeMap.americanIndian"          
[130] "JusticeMap.asian"                   
[131] ""                   
[132] "JusticeMap.hispanic"                
[133] "JusticeMap.multi"                   
[134] "JusticeMap.nonWhite"                
[135] "JusticeMap.white"                   
[136] "JusticeMap.plurality"               
[137] "Wikimedia"                          

The next set of code blocks demonstrate loading in different base maps by providing the layer’s name within the addProviderTiles() function. Copyright and source information are automatically added to the interactive map.

Take some time to experiment with different base maps by altering the example code.

What if you would like the user to be able to switch between some pre-defined base maps? This can be accomplished by loading in multiple layers using addTiles() or addProviderTiles(). You will then need to use addLayersControl() to create a widget to switch between the base maps. In order to reference the layers in the addLayersControl() function you will need to assign a unique name to each one using group. These names will be used in the widget. A collapse argument can be added to the addLayersControl() function to indicate whether or not it should collapse.

Add Points

Inow have a map with three base map layers that the user can choose between. I have also defined an initial extent and zoom level. However, I haven’t added any data yet.

To begin, I will add the smallest cities to the map using addMarkers(). Within the function, I must specify the data to be used. I am also defining the content of the **pop-u*p using the popup argument. This will simply print “Some Text” in each pop-up**.

Throughout the remaining examples, you will see the htmlEscape() function from the htmltools package used often. This functon is used to make sure that pop-up content is not incorrectly interpreted as HTML tags or code. Also, it should be used to avoid any security risks. In short, you should use this function when creating pop-ups.

Other symbology options are available for point data. In this example I am using addCircleMarkers() as opposed to addMarkers(). I am also now displaying all the city population groups using multiple addCircleMarkers() calls. Using the radius and color arguments, I am specifying sizes and colors for each symbol. I am setting the fillOpacity to 1 so that no transparency is applied and the stroke to FALSE so that no outline is included. I am also providing a group name for each point layer.

The pop-ups are more complicated than the above example. I am having the pop-up provide the city name and the city population. The “” tags are HTML tags used to bold text while the “
” tag indicates a line break. Note that these components are not wrapped in htmlEscape() since I do want them to be interpreted as HTML tags as opposed to text. I am using the base R paste0() function to combine all arguments into a single string. I am also indicating that I want comma separators included in the population numbers.

You may have noticed the use of ~ in the code. This allow for the data object to be passed on. So, I can just use the column name in the pop-up syntax and do not need to define the data object.

Similar to the base maps, you may also want the user to be able to turn the point layers on and off. This can be accomlished by adding a overlayGroups argument to addLayerConrols().

Add Polygons

I will now add some polygon layers to the map, which can be accomplished using the addPolygons() function. In this first example, I am adding the county-level percent forest data. I am not defining the symbology, so the default is used, which isn’t great for this use case.

leaflet() %>%
addTiles(group = "OSM") %>%
addProviderTiles("Esri.NatGeoWorldMap", group="ESRI") %>%
addProviderTiles("CartoDB.DarkMatter", group= "CartoDB") %>%
addPolygons(data=per_for_wm) %>%
addCircleMarkers(data=cities_5, group="2,500 to 9,999", radius=3, color="#ffffd4", stroke=FALSE, fillOpacity=1, popup = ~paste0("<b>", htmlEscape(NAME), "</b>","<br/>", htmlEscape(format(POP2010, big.mark=",")))) %>%
addCircleMarkers(data=cities_6, group="10,000 to 49,999", radius=5, color="#fed98e", stroke=FALSE, fillOpacity=1, popup = ~paste0("<b>", htmlEscape(NAME), "</b>","<br/>",htmlEscape(format(POP2010, big.mark=",")))) %>%

addCircleMarkers(data=cities_7, group="50,000 to 90,999", radius=7, color="#fe9929", stroke=FALSE, fillOpacity=1, popup = ~paste0("<b>", htmlEscape(NAME), "</b>","<br/>",htmlEscape(format(POP2010, big.mark=",")))) %>%
addCircleMarkers(data=cities_8, group="100,000 to 499,999", radius=9, color="#d95f0e", stroke=FALSE, fillOpacity=1, popup = ~paste0("<b>", htmlEscape(NAME), "</b>","<br/>", htmlEscape(format(POP2010, big.mark=",")))) %>%
addCircleMarkers(data=cities_9, group="500,000 to 999,999", radius=11, color="#993404", stroke=FALSE, fillOpacity=1, popup = ~paste0("<b>", htmlEscape(NAME), "</b>","<br/>",htmlEscape(format(POP2010, big.mark=",")))) %>%

addLayersControl(overlayGroups= c("2,500 to 9,999", "10,000 to 49,999", "50,000 to 90,999", "100,000 to 499,999", "500,000 to 999,999"), baseGroups = c("OSM", "ESRI", "CartoDB")) %>%
setView(lat= 42, lng=-105, zoom=5)