Leaflet in R

Some time ago we showed you how to display the results of your analyses on maps using ggmap. Today we’ll show you how to use the leaflet package in R to create interactive maps. To do this, we need the raster and sf libraries to load and process the input layers:

For our exercise, we will use the vector layers we used before: railways and roads. Let’s load them:

Let’s find the railway crossings:

Let’s load the raster. We will use the DEM for the Mazovia region:

The loaded raster does not have a coordinate system associated with it yet. Let’s correct that:

We will clip the NMT to the extent of the road layer:

Let’s open the map base with Leaflet and add implicit OSM map base tiles:

Let’s display the map:


Let’s add a raster DEM to the map, with a transparency of 0.8 function addRasterImage:


Let’s add a layer with roads (blue) and railways (red) using addPolylines. For vector layers, it is necessary to transform to a geographic layout with st_transform:


Previously, we intersected the two loaded layers, creating a point layer with intersections. Let’s add them to our map with addCircleMakers:


Our map now contains all the layers. The map is interactive – we can move around freely in it.

Czy zwróciliście uwagę że dla każdej funkcji dodającej warstwę zdefiniowaliśmy atrybut group. Wartości tego atrybutu wykorzystamy w ostatnim kroku dodając do mapy listę warstw. Podzielimy warstwy na te wyświetlane niezależnie (baseGroups) i te które mogą się nakładać (overlayGroups).

Did you notice that we defined a group attribute for each function to add a layer. We will use the values of this attribute in the last step when adding a list of layers to the map. We will divide the layers into those that are displayed independently (baseGroups) and those that can overlap (overlayGroups).

In the end, the map looks and works like this:

This post was just to give you an idea of what the leaflet package can do. It has many more features not mentioned today that you will have to discover for yourself. You can learn more about the features of the raster and sf libraries in our course GIS in R.

Leave a Reply

Your email address will not be published.

Translate using Google Translate»
Social media & sharing icons powered by UltimatelySocial

Podoba Ci się nasza strona? Odwiedź nasz profil