Using mapview

This package is pretty cool, and has a bunch of functionality. There are a number of vignettes online already, in particular check out the basic overview vignette here.

Main Functions

  • mapview - view potentially multiple spatial objects on a set of background maps
  • viewExtent - view extent / bounding box of spatial objects
  • viewRGB - view RGB true- or false-color images of raster objects
  • latticeView & sync - view small multiples of several potentially synchronised maps
  • slideView - view two overlaid raster objects with a horizontal slider to hide/reveal one of them
  • cubeView - 3D view of raster data cubes (e.g. space-time cube) with keyboard control over position of slices
  • plainview - view large rasters on a plain background (i.e. no background map)
  • mapshot - easily save maps (including leaflet maps) as html or png (or other image formats)

Spatial Data Supported in mapview

It is natively set to work with sf, which is great. Note it will plot raster objects as well!

  • sf (XY dimension only)
  • raster (Layer, Stack, Brick and SpatialPixels* / SpatialGridDataFrame)
  • sp (Points, Polygons, Lines and their DataFrame version)
  • satellite

Leaflet Compatible Functions

In addition, mapview provides some extra leaflet functionality:

  • addHomeButton - add zoom-to-layer buttons
  • addLogo - add a logo (or any image really) to a map
  • addFeatures - add features to a map (sf or sp). This is features type agnostic, meaning the same function can be used for points, lines and polygons
  • addMouseCoordinates - add mouse cursor postion information when moving over the map
  • addLargeFeatures - add large data to a map that would otherwise make the leaflet map irresponsive
  • popupTable, popupGraph & popupImage - popups of tables, grpahs and images for use with the leaflet add* functions

Using leaflet

You can also create leaflet maps, and they can be shared via html. This is a good way to provide dynamic spatial data, though bear in mind these html files can get large if you are trying to show a lot of data points or polygons.

The Basics

The leaflet website is excellent and should be the go-to for figuring out details. Below is a simple example building on some of the functions/data we worked with earlier in this workshop.

The main things to identify are:

  • What type of spatial data do you want to plot? (i.e., polygons, lines, markers, etc)
  • What format is that data? (works with sf or sp objects, or simple X/Y coordinates)
  • What base layers would you like to include? (see here for the possibilities)
  • How fancy do you want it to look? There are many extra options you can add using built in plugins, or custom Javascript.

Example: California Snow Course Stations

Let’s look at California snow course stations (check out the CDEC website). There’s a nice package called “sharpshooter” we can use to pull the locations and metadata for all these stations and plot them with a mapview and leaflet map.

library(sharpshootR)  #, CDECquery, CDECsnowQuery



# make a few changes for plotting purposes
snw<-dplyr::select(snw, course_number, id, elev_feet:longitude,apr1avg_in)
# make longitude negative!
snw$longitude <- abs(snw$longitude)*-1

str(snw) # check out data
## 'data.frame':    259 obs. of  6 variables:
##  $ course_number: int  1 2 3 5 417 311 4 298 285 9 ...
##  $ id           : Factor w/ 259 levels "3LK","ABN","ABY",..: 174 132 228 139 40 138 83 75 225 66 ...
##  $ elev_feet    : num  6700 6200 5850 6600 6450 6200 5900 5700 5500 7200 ...
##  $ latitude     : num  41.4 41.8 41.4 41.2 41.6 ...
##  $ longitude    : num  -123 -122 -123 -123 -123 ...
##  $ apr1avg_in   : num  35.1 16.6 13.1 31.5 35.2 27.4 24.5 17.6 29.2 33.1 ...

mapview Map

The nice thing is a mapview map is very simple to code compared to a leaflet map. See below.

mapviewOptions(fgb = FALSE)
# make a sf type object:
snw_sf <- st_as_sf(snw, coords = c("longitude", "latitude"), crs=4326, remove = FALSE)

# the default color scheme is viridis
mapview(snw_sf, zcol="apr1avg_in","CDEC SNOW STATIONS")

leaflet Map

A leaflet map takes a bit more formatting, but the sky is the limit. We can make the map look pretty much exactly as we’d like, there are far fewer limitations.


# add color palette
pal <- colorNumeric(
  palette = "GnBu",# can change to whatever: "RdBu", "GnBu"
  domain = snw$apr1avg_in

# Make a leaflet map!
m <- leaflet() %>% addTiles() %>% 
  #setView(lng = -120.8, lat = 39, zoom = 8) %>%  if you want to preset the view/zoom default
  addProviderTiles("Esri.WorldImagery", group = "ESRI Aerial") %>%
  addProviderTiles("Esri.WorldTopoMap", group = "Topo") %>%
  # add scale bar
  addMeasure(position = "topright",
             primaryLengthUnit = "meters",
             primaryAreaUnit = "sqmeters",
             activeColor = "#3D535D",
             completedColor = "#7D4479") %>%

addCircleMarkers(data=snw, group="CDEC Snow",
                 lng= ~longitude, lat= ~latitude, # the spatial data, requires "~" here because it's NOT sp or sf object
                 popup=paste0("<strong>","Course ID: ","</strong>", 
                              snw$course_number, "<br><strong>", "Name: ",
                              "</strong>", snw$id, "<br><strong>", "Elev (ft): ",
                              "</strong>", snw$elev_feet, "<br><strong>", 
                              "Apr-1 Avg: ", "</strong>", snw$apr1avg_in),
                 stroke=TRUE, weight=0.6,radius=8,
                 fillOpacity = 0.5, color="black",
                 fillColor= ~pal(apr1avg_in)) %>% # mapping to the color palette 

  # add controls for basemaps and data
    baseGroups = c("ESRI Aerial", "Topo"),
    overlayGroups = c("CDEC Snow"),
    options = layersControlOptions(collapsed = T))