From the course: Creating Maps with R

The basics of using Leaflet

From the course: Creating Maps with R

The basics of using Leaflet

- [Narrator] Leaflet is an awesome R package that allows us to build interactive maps using just R code. How is this possible? Well, the Leaflet package is an example of an HTML widget package. HTML widget packages wrap JavaScript libraries, in this case Leaflet, and allow us to use those JavaScript libraries writing only R code. The interactive maps that you build with Leaflet can be inserted into R Markdown documents, and into Shiny apps. If you want to learn more about HTML widgets in general, then I have a course dedicated to this topic, that covers Leaflet and four other HTML widget packages. But let's look at the basics of using Leaflet. So I've opened the script in the "05_01b Project", and I'm going to run the code on Line 7, through 1. And we'll start our Leaflet map with the Leaflet function, which gives us a gray rectangle with plus and minus buttons for zooming into our map when we add additional layers. And the first layer I'm going to add, is with the "addProviderTiles" function. This function allows me to add basemaps. All of the basemaps are available inside of the "providers" object. So if we type "providers" and "$", we see these named "provider" tiles. This website allows you to interactively compare the different basemaps available. I've zoomed in on my home city of Bristol, with the default "OpenStreetMap.Mapnik". And I just wanted to compare two different basemaps. "Thunderforest.Transport", which shows the human information for transport links in a city. If I scroll down to "Thunderforest.Landscape", that's going to include additional physical geometry in the form of contour lines. So now I'm back inside of R studio. Let's go and use one of the Shapefiles from Esri. I'm going to use "WorldPhysical". There, we've got basemaps added to our map. What I want to do now is, I want to add the outlines of the countries in the "world_sf" dataset. So. We'll pipe this, into "addPolygons". Data is equal to "world_sf". Now the defaults for Leaflet are fairly ugly. The lines in a map are too thick, and the colors aren't great, but we're focusing on the basics of using the package here. I wanted to show you how we would access columns in our dataset. So let's say I wanted to label each of the countries, when I hover over the country. I'm going to add the argument "label", and I'm going to give the name of the column, "name". And I get an error message, "object 'name' not found". This is because in a Leaflet package, we do not use naked column names. We need to use tildes. So if I put a tilde here, and now I hover it over Antarctica, you can see I get a label. And that's everything that you need to know in order to start using the Leaflet package.

Contents