Leaflet Viewer

leaflet


Leaflet is an interactive mapping package

  • view your spatial data in the Viewer pane of R Studio
  • based on a javascript library - leaflet.js
    • the most common library for making web maps.

Later in this course we will use leaflet to create interactive maps.

Create leaflet viewer

The leaflet() function creates a blank, interactive map canvas in your R Studio Viewer pane.

You can add elements to the map canvas using the generic addControl() function. Some of the more common functions:

  • To add a basemap
    • addProviderTiles()
    • Most commonly, you will add a pre-existing basemap as a background for your map. You can choose from many basemap providers
  • To add a point layer
    • addCircleMarker()
    • addMarker()
  • To add a line layer
    • addPolylines()
  • To add a polygon layer
    • addPolygons()

Map location

Once you add a layer, the map automatically zooms to the extent of the layer.

  • To change the extent
    • fitBounds(lng1, lat1, lng2, lat2) where
      • lng1, lat1 = SE corner of the map
      • lng2, lat2 = NW corner of the map
  • To center the map on a point and define zoom level
    • setView(lng = , lat = , zoom = )

In-class exercise: View Georgia schools on a map

Step 1.

At the top of your ga_schools script, make sure that tidyverse, sf, leaflet are all added.

Re-import the schools dataset with all variables

(comment out select(school, long, lat, total_enroll))

Step 2.

Create leaflet map with a baselayer

leaflet() |>
  addProviderTiles(provider = "CartoDB.Positron") 

Step 2.1

Define the extent of the map explicitly

leaflet() |>
  addProviderTiles(provider = "CartoDB.Positron") |>
  fitBounds(-84.3761, 33.7257, -80.3761, 36.7257)

Step 2.2

Center the map on Atlanta

leaflet() |>
  addProviderTiles(provider = "CartoDB.Positron") |>
  setView(lng = -84.3761, lat = 33.7257, zoom = 8)

Step 3.

Add Georgia schools to the map and let the map define the view by the extent of the point layer.

leaflet() |>
  addProviderTiles(provider = "CartoDB.Positron") |>
  addCircleMarkers(data = ga_schools_shp)

Style your leaflet map

To style your map:

  • add parameters to the addControl() function to define the colors, size, opacity, etc.
    • type ??addControl in the Console.

For example, these are some of the most commonly used style choices for a circle marker:

addCircleMarkers(

  • data = spatial_dataframe,
  • radius = 10,
  • stroke = TRUE,
  • color = “#03F”,
  • weight = 5,
  • opacity = 0.5,
  • fill = TRUE,
  • fillColor = color,
  • fillOpacity = 0.2 )


  • stroke refers to the outline of the circle or polygons
  • color refers to the outline color
  • weight refers to the thickness of the outline
  • opacity refers to the transparency of the outline, from 0( transparent) to 1(opaque)
  • fill refers to the inside of the circle or polygon
  • fillColor refers to the inside color

You can define colors with the hex code, or by calling one of the color names included in base R.

addPolygons(

  • data = spatial_dataframe,
  • stroke = TRUE,
  • color = “#03F”,
  • weight = 5,
  • opacity = 0.5,
  • fill = TRUE,
  • fillColor = color,
  • fillOpacity = 0.2)

In-class exercise: Style Georgia schools map

Step 1.

Define size of circles by the enrollment.

leaflet() |>
  addProviderTiles(provider = "CartoDB.Positron") |>
addCircleMarkers(data = ga_schools_shp,
                   radius = ~ total_enroll/300)

Step 2.

Color points by title 1 school status.

leaflet() |>
  addProviderTiles(provider = "CartoDB.Positron") |>
addCircleMarkers(data = ga_schools_shp,
                   radius = ~ total_enroll/300,
                   color = ~ case_when(title1_school_status == "2-Title I targeted assistance school" ~ "#5ab4ac",
                                       title1_school_status == "5-Title I schoolwide school" ~ "#3288bd",
                                       title1_school_status == "6-Not a Title I school" ~ "#fc8d59",
                                       TRUE ~ "#e5e5e5"))

Add a popup to your leaflet map


popup parameter defines the text that displays when you click on an object in your leaflet map.

  • all variables from your data
  • combine it with text using the paste() function.

popup = paste("School: ", ga_schools_shp$school, "<br> Enrollment: ", ga_schools_shp$total_enroll)

Notice

Notice

  • Put text within quotes
  • Use dataframe$ to call the variables
    • Note: you can add the data to the leaflet(ga_schools_shp) function instead of to addCircleMarkers() and then you don’t need to use dataframe$ to call a variable. But this only works if your map only has 1 layer.
  • <br> is the break html tag - it starts a new line

In-class exercise: Add a popup

Step 1.

Add popup with school name

leaflet() |>
  addProviderTiles(provider = "CartoDB.Positron") |>
  addCircleMarkers(data = ga_schools_shp,
                   radius = ~ total_enroll/300,
                   popup = paste("School: ",
                               ga_schools_shp$school, 
                               "<br> Enrollment: ", 
                               ga_schools_shp$total_enroll),
                   color = ~ case_when(title1_school_status == "2-Title I targeted assistance school" ~ "#5ab4ac",
                                       title1_school_status == "5-Title I schoolwide school" ~ "#3288bd",
                                       title1_school_status == "6-Not a Title I school" ~ "#fc8d59",
                                       TRUE ~ "#e5e5e5"))

Independent Activity: add polygons

Add the school district polygon layer to the map

  • Add the school districts spatial (ga_sd_pop) to your map
    • Use addPolygons()
  • Style the polygons
    • no fill
    • define the weight and and color of the outline
  • Add a popup with the School District name
  • Extra credit Add the Student Poverty Rate to the popup, format the poverty rate as a percent using the scales package

Additional, Optional Activity:

Create a new script to make a map of your choosing using spatial data and census variables from tidycensus.

Some suggestions:

  • A map of counties in Nebraska, colored by Median Household Income from ACS 1-year
  • A map of census tracts in Hinds County, Mississippi (Jackson), colored by Vacancy Rate
  • A map of school districts Cook County, Illinois (Chicago), colored by Percent Hispanic or Latino