Create a leaflet map using R

Leaflet R package

Hey!

Today I would like to introduce you to the leaflet package for R. This package makes it easy to integrate and control Leaflet maps in R. In other words: You can create beautiful Leaflet maps with your data from inside R, without any knowledge of JavaScript, HTML, CSS, etc… Sounds amazing, right? This is how it works…
First let’s prepare some data:

library(raster)
#get boundaries
usa <- getData("GADM", country="USA", level=2)
#add random data
usa$randomData <- rnorm(n=nrow(usa), 150, 30)

The fastest way to get to some arbitrary data, is to load the raster package and download administrative boundaries of a country of your choice using the getData() function. Note that country boundaries come without any additional data (like population, income, etc..). Since we later want to visualise some data on our map using some colors and pop-ups, I added a new column to the SpatialPolygonsDataFrame and filled it with random data using the rnorm function.

Create the map

The easiest way to create an HTML page that contains a leaflet map is to use RMarkdown. For this purpose go to New File -> RMarkdown -> HTML. This is how the final RMarkdown document looks like:

---
title: "Leaflet with R 101"
output: html_document
---

```{r, echo=F, warning=F, message=F}
#load leaflet package for R
library(leaflet)
library(raster)

#arbitrary data (code from above)
usa <- getData("GADM", country="USA", level=2)
usa$randomData <- rnorm(n=nrow(usa), 150, 30)

#create a color palette to fill the polygons
pal <- colorQuantile("Greens", NULL, n = 5)

#create a pop up (onClick)
polygon_popup <- paste0("<strong>Name: </strong>", usa$NAME_1, "<br>",
                        "<strong>Indicator: </strong>", round(usa$randomData,2))

#create leaflet map
  map = leaflet() %>% 
      addProviderTiles("CartoDB.Positron") %>% 
      setView(-98.35, 39.7,
              zoom = 4) %>% 
      addPolygons(data = usa, 
                  fillColor= ~pal(randomData),
                  fillOpacity = 0.4, 
                  weight = 2, 
                  color = "white",
                  popup = polygon_popup)
map
```

As you can see it the code is short and quite intuitive:

leaflet() initialises a new leaflet map, tiles/basemape can be added using the addTiles() or addProviderTiles() functions. In my example I included a basemap provided by CartoDB called “Positron”. Once you set the view and the zoom level using the setView() function, you can overlay your data with the addPolygons() function. And that’s it! Click on KnitHTML and view the final result in your browser:

Leaflet R package

I hope you enjoyed this rather short introduction into the very powerful leaflet package for R. If you are intrested in more detailed tutorials or code examples, please leave a comment below or visit this official Leaflet for R – Introduction.

Cheers

Martin

 

About This Author

Martin was born in Czech Republic and studied at the University of Natural Resources and Life Sciences, Vienna. He is currently working at an Earth Observation Company in Austria, specialised in Land Monitoring. His main interests are: Open-source applications like R, (geospatial) statistics and data-management, web-mapping and visualization. He loves travelling, geocaching, photography and TV series.

5 Comments

You can post comments in this post.


  • Martin you also have a great blog with very good articles. Liked leaflet mapping. Thank you for sharing. I am definitely going to follow you. I am also doing Master degree, like you.

    Pramod Mishra 2 years ago Reply


  • Martin, this is very helpful. Do you know how we can inset a hyperlink in the popup. I have a column with the hyperlink tags and want to put that in the popup. Eg in you case can we link the Name to some website?? Thanks for your help in advance.

    Luz 2 years ago Reply


    • Unfortunately I can’t insert any code inside a comment.
      But if you send you me an email: martin@gis-blog.com , I will send you the code snippet you need.

      cheers Martin

      Martin 2 years ago Reply


  • Hi Martin,

    I am trying to generate an HTML page with a simple leaflet map but the map does not render. Could you please tell me if there any additonal step that I have to follow? The code I am using is as follows:


    title: “Leaflet Map”
    output:
    html_document:
    self_contained: no

    “`{r results=’asis’, echo = FALSE}
    library(leaflet)
    rand_lng = function(n = 10) rnorm(n, -93.65, .01)
    rand_lat = function(n = 10) rnorm(n, 42.0285, .01)
    m = leaflet() %>% addTiles() %>% addCircles(rand_lng(50), rand_lat(50), radius = runif(50, 10, 200))
    m

    KV 1 year ago Reply


    • I tried your code (with a small adjustment – I edited the “` infront of the {} curly brackets and it works fine.
      What error message are you recieving?


      title: “Leaflet Map”
      output:
      html_document:
      self_contained: no

      “`{r results=’asis’, echo = FALSE}
      library(leaflet)
      rand_lng = function(n = 10) rnorm(n, -93.65, .01)
      rand_lat = function(n = 10) rnorm(n, 42.0285, .01)
      m = leaflet() %>% addTiles() %>% addCircles(rand_lng(50), rand_lat(50), radius = runif(50, 10, 200))
      m

      Martin 1 year ago Reply


Post A Reply

*