Interactive Mapping in the Leaflet package

Here we will be looking at how to map spatial data using the ‘leaflet’ package in R studio. This package allows you to create interactive maps for your data. Viewers of these maps can zoom in & out, click on markers for more information, and other edits.

This tutorial will go through mapping point data and steps for editing layers and markers on your map.

Setting Up Your Computer

1. Download R studio

If you don’t already have R & RStudio running on your computer, you will have to download the software for this exercise. R is free and easily accessbile software that can be dowloaded here.

2. Set up your working directory

This can be selected in the “session” tab in RStudio, but it can also be set up with the setwd() function by using a file path (eg. “H:/tutorial-leaflet”).

3. Packages to Install in R studio

Below is a list of all packages needed for the following exercise. If you do not already have access to these, use the install.packages() function for each. Then the library() function allows you to load packages you have installed into your R environment.

library(tidyverse)
library(htmltools)
library(leaflet)
library(leaflet.extras)
library(sf) #replaces 'sp' package, if you have code with sp code, there should be an evivalent function in sf
library(RColorBrewer)

Basemaps

For your interactive map you will need a basemap. With leaflet there are a number of options, the automatic basemap (openstreet maps) and other types that you can select. The leaflet() function creates the interactive plot and a basemap “Tile” is added. Follow the steps below and see how the different basemaps can be interacted with.

Option 1: automatic leaflet basemap

m <- leaflet() %>%
  addTiles()

Option 2: Use another basemap with the addProviderTiles() function

The full set of tile options are available to see here, otherwise you can just use options from providers$ function.

m <- m%>% addProviderTiles(providers$CartoDB.Positron)

Point data

Now you need to plot your data points onto your interactive basemap.The example below will go through the basics of plotting point data in leaflet before giving an overview of the different additional details you can incorporate with leaflet.

The data used for this tutorial is port location data published by the Department of Housing, Local Government and Heritage in Ireland. It has a CC BY 4.0 license (Creative Commons) and can be downloaded in csv format here.

Primary Steps

  1. Read in point data
  2. Investigate data
  3. save as a spatial object

1. Read in Point Data

ireland_ports<- read.csv("C:/Users/35385/Desktop/tutorial-data/Ports_Harbours_and_Shipping.csv")

2. Investiagte Data

head(ireland_ports, 2)
##          X       Y              NAME
## 1  -683278 6944823       Arklow Port
## 2 -1053249 6742474 Bantry Bay (Port)
##                                                                URL category
## 1 http://www.worldportsource.com/ports/IRL_Port_of_Arklow_3201.php Regional
## 2                                     http://www.bantrybayport.com Regional
##   Last_Updated                         Policy01_Name
## 1         2014 Ports, Harbours and Shipping Policy 2
## 2         2014 Ports, Harbours and Shipping Policy 2
##                             Policy02_Name
## 1 Ports, Harbours and Shipping Policy 3\n
## 2 Ports, Harbours and Shipping Policy 3\n
##                             Policy03_Name Policy04_Name      Policy05_Name
## 1 Ports, Harbours and Shipping Policy 4\n  ORE Policy 7 Fisheries Policy 6
## 2 Ports, Harbours and Shipping Policy 4\n  ORE Policy 7 Fisheries Policy 6
##   Owning_Organisation
## 1               MaREI
## 2               MaREI
##                                                                                  Metadata_Links
## 1 http://data.marine.ie/geonetwork/srv/eng/catalog.search#/metadata/ie.marine.data:dataset.4406
## 2 http://data.marine.ie/geonetwork/srv/eng/catalog.search#/metadata/ie.marine.data:dataset.4406
##   Map_Features_Key_Layer_Title OBJECTID
## 1             Ports of Ireland        1
## 2             Ports of Ireland        2

3. Save as Spatial Object

Make a sf object using cordinates and the correct crs

ireland_ports_sf <- st_as_sf(ireland_ports, coords = c("X", "Y"), crs = 3857)

Change crs to a universal projection, WGS 84 EPSG:4326

ireland_ports_wgs84 <- st_transform(ireland_ports_sf, crs = 4326)

Then, extract the transformed coordinates and add them back into the data frame.

ireland_ports$lon <- st_coordinates(ireland_ports_wgs84)[,1]
ireland_ports$lat <- st_coordinates(ireland_ports_wgs84)[,2]

Mapping on Leaflet

  1. make a marker for from point data
  2. add pop up information
  3. add marker label
  4. change the marker syle
  5. other edits

1. Make a Marker from Point Data

Here, you add point locations to your existing basemap map ‘m’

m2<- m%>% addMarkers(data=ireland_ports, lat=ireland_ports$lat, lng=ireland_ports$lon)

2. Add Popup Information

Add values from one of your columns to each marker popup. In the code below the column with the port name data is selected for the popup option.

m3<- m %>% addMarkers(data=ireland_ports, lat=ireland_ports$lat, lng=ireland_ports$lon,popup=ireland_ports$NAME)

3. Add Label Information

Here we do the same, but with a label instead of a popup. Label information will appear when you hover your mouse over the location marker. Whereas, popup information will only appear once clicked on.

m4<- m %>% addMarkers(data=ireland_ports, lat=ireland_ports$lat, lng=ireland_ports$lon,label=ireland_ports$NAME)

4. Change Marker Style

functions such as addCircleMarkers & addAwsomeMarkers() give you other options for style of marker on your map. Circle markers can be useful as color & radius etc can be used to indicate underlying data.

First, define your colour plaette

pal <- colorFactor(palette = c("green", "orange", "purple"), domain = ireland_ports$category)

Then, modify the map code to use the color palette for circle markers

m5 <- m %>%
  addCircleMarkers(data = ireland_ports, 
                   lat = ~lat, 
                   lng = ~lon, 
                   fillOpacity = 0.8,
                   radius = 5, 
                   color = ~pal(category),    # Assign color based on category
                   fillColor = ~pal(category), 
                   label=ireland_ports$category) # Fill color based on category

Or, if you would like to keep other information on your marker label you can always provide a legend for the colour markers. In this example we will italicise the port name text in the label.

First, save you palette of marker colours and the marker values as the legen colours and values.

legend_colors <- pal(unique(ireland_ports$category))
legend_labels <- unique(ireland_ports$category)  # you can also set labels using a list with c()

Then make your map with a legend added in.

m6 <- m %>%
  addCircleMarkers(
    data = ireland_ports, 
    lat = ~lat, 
    lng = ~lon, 
    fillOpacity = 0.8,
    radius = 5, 
    color = ~pal(category),    # Assign color based on category
    fillColor = ~pal(category), 
    label = ~(lapply(paste("<i>",NAME, "</i><br>"), HTML))#edit font of label text
    ) %>%
  addLegend(
    position = "bottomleft",
    colors = legend_colors,
    labels = legend_labels,
    title = "Port Category"
  )

5. Other Edits

There are many ways you can edit markers based on what works best for your data. More examples for marker styles can be found here.

Further information on how to use popups and labels can be found here.

References

Cheng J, Sievert C, Schloerke B, Chang W, Xie Y, Allen J (2024). htmltools: Tools for HTML. R package version 0.5.8.9000. [https://github.com/rstudio/htmltools]

Cheng J, Schloerke B, Karambelkar B, Xie Y (2024). leaflet: Create Interactive Web Maps with the JavaScript ‘Leaflet’ Library. R package version 2.2.2.9000, [https://github.com/rstudio/leaflet, https://rstudio.github.io/leaflet/]

Neuwirth, E. (2022). ColorBrewer Palettes, R Package RColorBrewer Version 1.1-3.[https://CRAN. R-project. org/package= RColorBrewer]

Pebesma E (2018). “Simple Features for R: Standardized Support for Spatial Vector Data.” The R Journal, 10(1), 439–446. [https://doi.org/10.32614/RJ-2018-009]

Roche M. Ports of Ireland (2022),Department of Housing, Local Government, and Heritage. [https://data-housinggovie.opendata.arcgis.com/api/download/v1/items/128dd0e242774ac2889d5fd8220324de/geojson?layers=0]

Wickham H, Averick M, Bryan J, Chang W, McGowan LD, François R, Grolemund G, Hayes A, Henry L, Hester J, Kuhn M, Pedersen TL, Miller E, Bache SM, Müller K, Ooms J, Robinson D, Seidel DP, Spinu V, Takahashi K, Vaughan D, Wilke C, Woo K, Yutani H (2019). “Welcome to the tidyverse.” Journal of Open Source Software, 4(43), 1686.[https://doi.org/10.21105/joss.01686]