I am using
library(tmap)
qtm("London")
to get a map of London but can't find a way to get it in a shape?
tm_shape
Otherwise, I can only have it in view mode, not in plot mode.
I am using
library(tmap)
qtm("London")
to get a map of London but can't find a way to get it in a shape?
tm_shape
Otherwise, I can only have it in view mode, not in plot mode.
Yes, that is correct. You have to do it another way to get a map layer in tmap_mode("plot")
.
In tmap_mode("view")
you can just do it like that:
tm_shape(lnd) + tm_polygons(alpha = 0.7, col = "Pop_2001", legend.show = FALSE) +
tm_basemap(server = c('OpenStreetMap'))
With tm_basemap(server = c('OpenStreetMap'))
not being necessary, but I've put it anyway, because here you can change the basemap, for example to stamen
.
For tmap_mode("plot")
you have to download the tiles manually. There are several ways to do that.
1. The tmaptools
-package offers a function to do that read_osm()
. To get the Tiles you do lonmap <- bb("London") %>% read_osm(type = "osm")
, which returns a raster object.
2. Another alternative is openmap()
from the OpenStreetMap
-package, which would look like that:
london <- bb("London")
lonmap <- openmap(upperLeft = london[3:4],
lowerRight = london[1:2],
type = "osm",
mergeTiles = TRUE)
3. And of course there is get_map()
from the ggmap
-package for which you now need an API-key. This can't be put directly into tm_shape()
however.
But to be honest read_osm()
and openmap()
both give me the error
java.lang.NullPointerException
and I haven't been able to find a solution to it.
4. So I use even another one: The getTiles()
function from the cartography
-package. getTiles
only takes sf
or sp
objects and returns a RasterBrick
-object
library(tmap)
library(cartography)
lonmap <- getTiles(x = lnd, type = "osm")
tmap_mode("plot")
tm_shape(lonmap) + tm_rgb() + tm_shape(lnd) +
tm_polygons(alpha = 0.5,col = "Pop_2001", legend.show = FALSE)
Which gives you this:
A workaround for being able to use a bounding box would be:
lonmap <- bb("London") %>%
matrix(ncol = 2, byrow = TRUE) %>%
SpatialPoints(proj4string = CRS("+init=epsg:4326")) %>%
getTiles(type = "osm")
The lnd
, is a SpatialPolygonsDataFrame
. Never mind the content. You can get it from here:
https://github.com/Robinlovelace/Creating-maps-in-R/blob/master/data/london_sport.shp