4.2 Interactive Maps
As introduced in chapter Making Maps, an interactive Map is the fundamental building block of ArcGIS. In R, we need to do some extra work to create such an interactive map, but this extra work sometimes means just one line of code. There are multiple packages that simplify creating maps:
mapview
and tmap
both build on the package leaflet
, which in turn builds on leaflet, an open source JavaScript Library for interactive maps. There really is not much need to learn leaflet
, since using mapview
or tmap
is much simpler.
The package plotly
builds on plotly, a very versatile graphics library that provides an API for R
, Python
and Julia
. It is an amazing tool, but we will focus more on mapview
and tmap
.
4.2.1 Package mapview
The package mapview
is highly automated and you get a very decent map when calling the function mapview::mapview
on your geodata, without any additional arguments. The aim of the package is to be quick and easy, as emphasized in the documentation:
It’s main goal is to fill the gap of quick […] interactive plotting to examine and visually investigate both aspects of spatial data, the geometries and their attributes.
library(arc2r)
library(sf)
library(raster)
library(mapview)
## GDAL version >= 3.1.0 | setting mapviewOptions(fgb = TRUE)
This next line of code generates a representation of your data (in this case, gemeindegrenzen_zh
), much like the default map in ArcGIS.
mapview(gemeindegrenzen_zh)
If the emphasis lies on creating a highly customized map, then tmap
may be more appropriate.
4.2.2 Package tmap
Like mentioned in the previous chapter, the package tmap
facilitates creating highly customized maps. But the greatest strength in tmap
comes from it’s versatility: All you need to do is specify how you want your data to be displayed, and tmap
can render this into an interactive map of a static one that you can print. All you need to do is change the mode
within the function tmap_mode()
to view
.
library(tmap)
tmap_mode("view")
## tmap mode set to interactive viewing
As shown in chapter ??, the tmap
syntax very similar to ggplot2
s, in the sense that connect “layers” using a +
sign.
tm_shape(gemeindegrenzen_zh) +
tm_polygons()