Tutorial: How to put dots on a Leaflet map with R

Print More

It’s useful to quickly map a dataset of locations, and to do it in the same environment that you’re doing your data analysis. There are many quick and easy ways to map latitude and longitude markers with R, such as using RgoogleMaps, ggmaps or the maps package.

But those packages generate static images. Sometimes you need to zoom in or pan around a map for greater comprehension.

At TrendCT, we use Leaflet, an open source Javascript library, to generate our maps.

It’s extremely versatile for building many types of interactive maps. The folks behind RStudio — a user interface to help you work with the statistical analysis language R — have been creating packages that integrate with popular Javascript libraries like Leaflet. It’s great for people with no knowledge of Javascript who want to make interesting interactives using R. And there is excellent documentation.

This tutorial will show you how to take a dataset with latitude and longitude columns, map it and style it — all with just a few lines of code in R.

Difficulty Level

Intermediate. Go through the beginner tutorial to get R and RStudio installed before you begin.

Download the dataset, set the working directory, and follow along. You can also skip straight to the full script.

Getting started

Packages are collections of user-created R scripts, data and functions that simplify complex operations. There are thousands of them for all sorts of repetitive processes. TrendCT made a package to clean Connecticut town names. The directory where packages are stored is called the library. R comes with a standard set of packages. Others are available for download and installation. Once installed, they have to be loaded into the session to be used. There are two steps to working with packages:

  • Downloading the package to your computer with install.packages("package_name") — after which you never have to re-download it (unless you want to because there’s been an update).
  • Load it to your session with library(package_name) or require(package_name). Every time you start up R or RStudio, you have to reload the package to your computer’s memory by calling its library/directory.

Start by downloading and installing the Leaflet package from the servers at CRAN, the Comprehensive R Archive Network. You’ll need one more package, dplyr, for some piping functions.

A note on Pipes in R

The piping operator %>% is a feature that streamlines coding in R.

It’s easier to wrap your head around it if you think of coding grammatically. Normal coding in R is rigid declarative sentences: “Bob is 32. Nancy is 4 years younger than Bob.” Coding with the pipe operator: “Nancy is 4 years younger than Bob, who is 32.” Pipes are a comma (or a semi-colon, if you want) that lets you create one long, run-on sentence.

Making a map with a marker

Explaining the R code

  • leaflet() initializes the leaflet workspace
  • addTiles() by itself will bring in the default OpenStreetMap tiles.
    Note: OpenStreetMaps is a wonderful and free open-source service. Their only stipulation for using their tiles is to be sure to credit and link to them in the map.
  • setView() is pretty self-explanatory but is simpler to implement.
  • addMarkers with some specific parameters.

Note: The order of commands is important. A view can’t be set unless there are tiles established first.

How to put it online
Screen Shot 2015-06-22 at 11.18.44 AM

If you want to share your map outside of the RStudio environment, simply click on the Save as Web Page option in Export. It will generate an HTML file that expands to the whole screen of the browser. From here, you can upload it to your server and iframe it to the appropriate height and width you want.

A note about file sizes

Screen Shot 2015-06-22 at 11.13.41 AM When comparing the size of the HTML files, the R-produced version of the map is larger in size because it is bringing all the Javascript and CSS inline into the HTML.

However, when looking at how much data is actually downloaded to load the map html, the differences aren’t as drastic.


It’s just something to keep in mind.

It’s always better in terms of efficiency and customization to code from scratch. Here’s a useful tutorial for reference.

But on a deadline, sometimes user experience is sacrificed.

Multiple locations from a CSV

Screen Shot 2015-06-22 at 1.20.46 PM Let’s make a map with a list of locations from the file ctlist.csv.

  • The spreadsheet ctlist.csv was saved to the variable ct
  • The dataframe ct was added within the leaflet() function.
  • Then it pipes to the addTiles function with a link to a set of dark map tiles. Here’s a large list of map tiles you can substitute.
  • View and zoom is set the same as before.
  • Then it pipes to the addCircles function, passing it the names of the latitude and longitude column in the ct dataframe, as well as where to find the text for the pop-up information, and the parameters to set the style of the circles on the map.


Adding a legend to the map

  • Pipe in addLegend()

Five lines of code in R to make a complete map.

Compare that to 585 lines of HTML, CSS, and Javascript.

You could specify a palette of colors and it would show a range of colors if needed in the legend and map. But for now we just have one type of dot on the map, so we specify the variables. To get a good look at the legend options, type ?addLegend in the console of R.

But we’ll get into that next time when we discuss mapping with choropleths.

What do you think?

  • Limbu Malongo Limbu

    Great tutorial

  • Aditya Kamath

    Hi Andrew. Thanks for this tutorial. I keep getting this error when I try to execute the exact code that you have provided here and display the map. The error reads – “Error in browseURL(x, …) : ‘url’ must be a non-empty character string”. I’d be grateful if you could help me with this. Thank you!

  • nurandi

    Very useful tutorial 🙂

    I get error when saving map as web page:

    Error: pandoc document conversion failed with error 127
    In addition: Warning message:
    running command ‘ +RTS -K512m -RTS “C:Users870073AppDataLocalTempRtmp25itAkviewhtmla6c389cbccindex.html” –from markdown_strict –output “C:Users870073Desktopleaflet-test.html” –self-contained –template “C:Users870073AppDataLocalTempRtmp25itAkfilea6cd5e1592.html”‘ had status 127

    Do you have any suggestion?

    • Andrew Ba Tran

      Hm, not sure without seeing the code. My guess is that it has something to do with the version of RStudio. Are you using the latest release? Or perhaps you upgraded in the middle of your project?

      • nurandi

        Thanks, Andrew.
        Problem solved after re-install knitr and rmarkdown.

  • Ebrahim Jahanshiri

    Great tutorial Andrew.
    I was just wondering Is there any way to animate raster data on leaflet? I know how to add a raster layer stack but what if you want to animate the layers like a Gif.

  • Pippo

    Just the thing I needed, Thanks!

  • Omar Abdulkadir Mahadalle

    Thanks.. this helped me a lot!

  • Joe Foley

    Hello Andrew, Just made a pop-up map in very little time thanks to your tutorial. TAHNK YOU, AGAIN! But I have Q: I did it on Rstudio and used the RS “publish to web” feature. When I email to my phone though the dots do not scale up as I zoom in? In other words the more I zoom in the seemingly smaller the points I want to click on get. Any suggestions? Would it help if I tried to publish it on something like Netilify ?