I am a longtime fan of the mapview package. I use it repeatedly during a typical R work session to quickly visualize and interact with spatial data. Most of my time in RStudio is spent writing a regular R script. If I want to see mapview’s interactive map in a larger window, I simply mouse over to the Viewer pane, and pop the map out using either the “Zoom” button or the “Show in new window” button.
I have lately been using RMarkdown more. Mapview works as expected in RMarkdown, but I was missing the ability to pop out the interactive map from the resulting html in full-screen. For example, the below map cannot be viewed in full screen:
library(mapview)
library(tidyverse)
breweries = mapview::breweries #bring to local env't
breweries %>%
mapview(layer.name = "breweries")
Fortunately, the leaflet.extras package has the addFullscreenControl
function, but applying this function directly to a mapview object
does not work, because this function expects a leaflet map:
library(leaflet)
library(leaflet.extras)
breweries %>%
mapview(layer.name = "breweries") %>%
leaflet.extras::addFullscreenControl() #does not work
In this issue (38), mapview’s
author explains how to access the leaflet map component of the mapview
object via @map
. To my knowledge, this @map
cannot be called at the end of a pipe, but we can create a
mapview object first, access the leaflet map via @map
, and
then use leaflet.extras’ addFullscreenControl
function. The
following code does this, adding a full-screen control button to the
top-left of the map:
mv_breweries = breweries %>%
mapview(layer.name = "breweries")
mv_breweries@map %>%
leaflet.extras::addFullscreenControl() #works
One other thing. Sometimes, it’s useful to add multiple layers to the
same interactive map using the +
operator, as
described. To add full-screen control to mapview objects comprised
of multiple mapview objects, we access the leaflet map via
@map
from the final mapview object (i.e., not each
constituent mapview object).
For example, suppose we create one mapview object to visualize
breweries founded before 1800 and another for those founded after. We
can combine those two mapview objects using +
and add
full-screen control to the resulting mapview comprising both following
the code above.
summary(breweries$founded)
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## 1353 1693 1858 1805 1891 2013 144
mv_old_breweries = breweries %>%
filter(founded <1800) %>%
mapview(
layer.name = "old breweries",
col.regions = "orange",
color = "orange")
mv_new_breweries = breweries %>%
filter(founded >=1800) %>%
mapview(
layer.name = "new breweries",
col.regions = "blue",
color = "blue")
mv_old_and_new = mv_old_breweries +
mv_new_breweries
mv_old_and_new@map %>%
leaflet.extras::addFullscreenControl()
Again, the full-screen icon is on the top-left, allowing the user to interactively pop the map into full-screen mode.
Copyright © 2023 Michael D. Garber