Plotting DataCamp HQ

Interactive Maps with leaflet in R

Rich Majerus

Vice President of Strategy & Planning, Queens University of Charlotte

Plotting a Point

# add marker layer to map
leaflet() %>% 
     addTiles() %>% 
     addMarkers(lng = -73.98575, 
                lat = 40.74856)

Single marker example

  • Supplying Marker Data

    • Numeric data frame columns
    • Numeric vectors
  • addMarkers() Defaults

    • Centered on a single point
    • Zoomed to fit all points
Interactive Maps with leaflet in R

Plotting Multiple Points

dc_hq <- 
     tibble(
         hq  = c("DataCamp - NYC", "DataCamp - Belgium"),
         lon = c(-73.98575, 4.717863),
         lat = c(40.74856, 50.881363))
leaflet() %>% 
     addTiles() %>% 
     addMarkers(lng = dc_hq$lon, lat = dc_hq$lat)

Multiple markers example

Interactive Maps with leaflet in R

Plotting Multiple Points II

# When piping a data frame into the leaflet function, R will search 
# for columns named lat/latitude and lon/lng/long/longitude  
dc_hq  %>% 
     leaflet() %>% 
     addTiles() %>% 
     addMarkers() 
Assuming 'lon' and 'lat' are longitude and latitude, respectively

Multiple markers example

Interactive Maps with leaflet in R

Pop-ups

leaflet() %>% 
     addTiles() %>% 
     addMarkers(lng = dc_hq$lon, lat = dc_hq$lat, 
               popup = dc_hq$hq)

Markers with popups example

Interactive Maps with leaflet in R

Pop-ups II

leaflet() %>% 
     addTiles() %>% 
     addPopups(lng = dc_hq$lon, lat = dc_hq$lat,
               popup = dc_hq$hq)

Popups example

Interactive Maps with leaflet in R

Storing leaflet Maps as Objects

m <- leaflet() %>%
     addTiles()  %>% 
     setView(lng = dc_hq$lon[1], 
             lat = dc_hq$lat[1], 
             zoom = 12)

Storing maps as objects

# %>% leaflet objects to functions 
# to add or edit layers
m %>% addMarkers(lng = dc_hq$lon, 
                 lat = dc_hq$lat, 
                 popup = dc_hq$hq)

Adding to layers

Interactive Maps with leaflet in R

Let's practice!

Interactive Maps with leaflet in R

Preparing Video For Download...