Mapping with leaflet package

Cecilia Chen

2020-08-16

Introduction

Leaflet is a great way of showing maps.It’s actually a JavaScript library available as a package in R.It works efficiently across all major desktop and mobile platforms, can be extended with lots of plugins, has a beautiful, easy to use ad wekk-documentd API and a simple, readable source code that is a joy to contribute to. This step-by-step guide will quickly get you started on Leaflet basics, including setting up a Leaflet map, working with markers, polylines and popups, and dealing with events.

Firstly, install and library the leaflet package via the following code:


install.packages("leaflet")

library(leaflet)

Different types of maps

After install the package, I add leaflet and tiles to the object to get our first map of the world.


library(leaflet)

# Plot map of the world
map <- leaflet() %>%
  addTiles()
map

Zoom in to a particular area

Let’s try locate on Sydney. You can change the zoom level or position of the map with the setView(). Use the longitude and latitude which you want to have in the center of the map. You can tell the zoom parameter how detailed the map should be. Now the zoom level on map is 10. The higher the zoom level, more detail will be covered.


# Zoom in on specific location
map <- map %>%
  setView(151.2293, -33.84, zoom = 10)
map

More types of maps are avalible on http://leaflet-extras.github.io/leaflet-providers/preview/index.html


# Change map type
map %>% addProviderTiles(providers$Esri.DeLorme)
map %>% addProviderTiles(providers$Esri.NatGeoWorldMap)

Add pop up marker

Next, how about add markers for some well-known place such as Opera House in Sydney?


map_WithMarker <- map %>%
    addMarkers(lng=151.2293, lat=-33.84, popup="Sydney Opera House")

map_WithMarker

Add pop up window that stay open

What if you want to add a popup windows shows the detail of the address and show on map without click on the marker? Run the code below to add a popup window to the map that shows UTS’s address.


content <- paste(sep = "<br/>",
                 "Sydney Opera House",
                 "Bennelong Point, Sydney",
                 "NSW 2000")
                 
map_WithMarker %>%
    addPopups(lng=151.2293, lat=-33.84, content,
              options = popupOptions(closeButton = FALSE))

Customizing Marker Icons

How about a customised Marker for Opera House using Opera House logo? Using the code below, we can put Opera House Logo as marker on map. Simply use makeIcon function to import an icon from an URL or local file path. Then use the iconWidth and iconHeight argument to change the width and height of the icon.


Operahouse <- makeIcon(
    iconUrl = "http://www.pngmart.com/files/4/Sydney-Opera-House-PNG-Transparent-Image.png",
    iconWidth = 100, iconHeight = 75,
    iconAnchorX = 22, iconAnchorY = 94)

map_WithMarker %>% 
    addMarkers(lng=151.2293, lat=-33.84, icon = Operahouse)

Plot a Dataset

we’ve already tried to plot a single address on map, let’s now try to plot a dataset. quakes is the build in data set in R shows the Locations of Earthquakes of Fiji. The quakes dataset has 4 variables for each Station, the Latitude and Longitude of event, Depth (km) and Richter Magnitude.

We can take a look at the structure of the dataset using str function:


str(quakes)
#> 'data.frame':    1000 obs. of  5 variables:
#>  $ lat     : num  -20.4 -20.6 -26 -18 -20.4 ...
#>  $ long    : num  182 181 184 182 182 ...
#>  $ depth   : int  562 650 42 626 649 195 82 194 211 622 ...
#>  $ mag     : num  4.8 4.2 5.4 4.1 4 4 4.8 4.4 4.7 4.3 ...
#>  $ stations: int  41 15 43 19 11 12 43 15 35 19 ...

we can also run the code below to exam the first 20 raws from the quakes dataset:


data(quakes)

# Show first 20 rows from the `quakes` dataset
leaflet(data = quakes[1:20,]) %>% addTiles() %>%
  addMarkers(~long, ~lat, popup = ~as.character(mag), label = ~as.character(mag))

Customizing Marker Icons

You can provide custom markers in one of several ways, depending on the scenario. For each of these ways, the icon can be provided as either a URL or as a file path.

For the simple case of applying a single icon to a set of markers, use makeIcon().


greenLeafIcon <- makeIcon(
  iconUrl = "http://leafletjs.com/examples/custom-icons/leaf-green.png",
  iconWidth = 20, iconHeight = 20,
  iconAnchorX = 22, iconAnchorY = 94,
  shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png",
  shadowWidth = 20, shadowHeight = 20,
  shadowAnchorX = 4, shadowAnchorY = 62
)

leaflet(data = quakes[1:4,]) %>% addTiles() %>%
  addMarkers(~long, ~lat, icon = greenLeafIcon)

Plot markers as cluster

It seems that the map is too crowded as there are too many markers overlapping each other. How about showing the marker cluster according to the size of the map? Run the code below to show the number of markers as clusters, zoom in and zoom out to see the effect.


leaflet(quakes) %>% 
    addTiles() %>% 
    addMarkers(~long, ~lat, clusterOptions = markerClusterOptions())

Investigate more about the Package

There are many other ways you can play with the pack, such as categorise the data by size or color, build your own icon list and apply them to corresponding data, and use circles to plot the range.

For more detail about this package, please visit http://rstudio.github.io/leaflet/.