knitr::opts_chunk$set( collapse = TRUE, comment = "#>", warning = FALSE, message = FALSE, dpi = 300, tidy = "styler", dev = "ragg_png", out.width = "100%" ) # Cache for articles library(mapSpain) initcache <- mapSpain::esp_detect_cache_dir() cache_dir_here <- file.path(getwd(), "artcache") esp_set_cache_dir(cache_dir_here, verbose = FALSE)
mapSpain provides a powerful interface for working with imagery.
mapSpain can download static files as .png
or .jpeg
files (depending on
the Web Map Service) and use them along your shapefiles.
mapSpain also includes a plugin for R leaflet package, that allows you to include several basemaps on your interactive maps.
The services are implemented via the leaflet plugin leaflet-providersESP. You can check a display of each provider on the previous link.
An example of how you can include several tiles to create a static map. We focus here on layer provided by La Rioja's Infraestructura de Datos Espaciales (IDERioja).
When working with imagery, it is important to set moveCAN = FALSE
, otherwise
the images for the Canary Islands won't be accurate.
library(mapSpain) library(sf) library(ggplot2) library(tidyterra) # Logroño lgn_borders <- esp_get_munic_siane(munic = "Logroño") # Convert to Mercator (EPSG:3857) as a general advice when working with tiles lgn_borders <- st_transform(lgn_borders, 3857) tile_lgn <- esp_getTiles(lgn_borders, "IDErioja", bbox_expand = 0.5) ggplot(lgn_borders) + geom_spatraster_rgb(data = tile_lgn) + geom_sf(fill = NA, linewidth = 2, color = "blue")
Some tiles could be loaded with or without an alpha value, that controls the transparency of the object:
madrid <- esp_get_ccaa("Madrid", epsg = 3857) # Example without transparency basemap <- esp_getTiles(madrid, "IGNBase.Gris", zoommin = 1) tile_opaque <- esp_getTiles(madrid, "UnidadesAdm.Limites", transparent = FALSE) ggplot() + geom_spatraster_rgb(data = basemap) + geom_spatraster_rgb(data = tile_opaque) + theme_void()
Now let's check the same code using the tranparent = TRUE
option:
# Example with transparency tile_alpha <- esp_getTiles(madrid, "UnidadesAdm.Limites", transparent = TRUE) # Same code than above for plotting ggplot() + geom_spatraster_rgb(data = basemap) + geom_spatraster_rgb(data = tile_alpha) + theme_void()
Now the two tiles overlaps with the desired alpha value.
Another nice feature is the ability of masking the tiles, so more advanced maps can be plotted:
rioja <- esp_get_prov("La Rioja", epsg = 3857) basemap <- esp_getTiles(rioja, "IGNBase.Gris", bbox_expand = 0.1, zoommin = 1) masked <- esp_getTiles(rioja, "IGNBase.Todo", mask = TRUE, zoommin = 1) ggplot() + geom_spatraster_rgb(data = basemap, maxcell = 10e6) + geom_spatraster_rgb(data = masked, maxcell = 10e6)
mapSpain provides a plugin to be used with the leaflet package. Here you can find some quick examples:
library(leaflet) tenerife_leaf <- esp_get_nuts( region = "Tenerife", epsg = 4326, moveCAN = FALSE ) bbox <- as.double(round(st_bbox(tenerife_leaf) + c(-1, -1, 1, 1), 2)) # Start leaflet m <- leaflet(tenerife_leaf, elementId = "tenerife-earthquakes", width = "100%", height = "60vh", options = leafletOptions(minZoom = 9, maxZoom = 18) ) # Add layers m <- m %>% addProviderEspTiles("IDErioja.Relieve") %>% addPolygons(color = NA, fillColor = "red", group = "Polygon") %>% addProviderEspTiles("Geofisica.Terremotos365dias", group = "Earthquakes" ) # Add additional options m %>% addLayersControl( overlayGroups = c("Polygon", "Earthquakes"), options = layersControlOptions(collapsed = FALSE) ) %>% setMaxBounds(bbox[1], bbox[2], bbox[3], bbox[4])
A map showing the population density of Spain as of 2019:
munic <- esp_get_munic_siane( year = 2019, epsg = 4326, moveCAN = FALSE, rawcols = TRUE ) # Get area in km2 from siane munic # Already on the shapefile munic$area_km2 <- munic$st_area_sh * 10000 # Get population pop <- mapSpain::pobmun19 # Paste munic_pop <- merge(munic, pop[, c("cmun", "cpro", "pob19")], by = c("cmun", "cpro"), all.x = TRUE ) munic_pop$dens <- munic_pop$pob19 / munic_pop$area_km2 munic_pop$dens_label <- prettyNum(round(munic_pop$dens, 2), big.mark = ".", decimal.mark = "," ) # Create leaflet bins <- c(0, 10, 25, 100, 200, 500, 1000, 5000, 10000, Inf) pal <- colorBin("inferno", domain = munic_pop$dens, bins = bins, reverse = TRUE) labels <- sprintf( "<strong>%s</strong><br/><em>%s</em><br/>%s pers. / km<sup>2</sup>", munic_pop$rotulo, munic_pop$ine.prov.name, munic_pop$dens_label ) %>% lapply(htmltools::HTML) leaflet(elementId = "SpainDemo", width = "100%", height = "60vh") %>% setView(lng = -3.684444, lat = 40.308611, zoom = 5) %>% addProviderEspTiles("IDErioja") %>% addPolygons( data = munic_pop, fillColor = ~ pal(dens), fillOpacity = 0.6, color = "#44444", weight = 0.5, smoothFactor = .1, opacity = 1, highlightOptions = highlightOptions( color = "white", weight = 1, bringToFront = TRUE ), popup = labels ) %>% addLegend( pal = pal, values = bins, opacity = 0.7, title = paste0( "<small>Pop. Density km<sup>2</sup></small><br><small>", "(2019)</small>" ), position = "bottomright" )
The list esp_tiles_providers
includes the data of the available providers you
can use on functions described above. This list includes all the parameters
needed to replicate the API request. See the static url of each provider:
library(reactable) prov_names <- names(esp_tiles_providers) urls <- vapply(esp_tiles_providers, function(x) { # Create url allpars <- x$static q <- allpars$q rest <- modifyList( allpars, list( attribution = NULL, q = NULL ) ) rest_temp <- paste0(names(rest), "=", rest, collapse = "&") templurl <- paste0(q, rest_temp) if (grepl("rioja", q, ignore.case = TRUE)) { templurl <- q } templurl }, FUN.VALUE = character(1)) df <- data.frame( provider = prov_names, static_url = urls ) rownames(df) <- NULL reactable(df, filterable = TRUE, searchable = TRUE, showPageSizeOptions = TRUE, striped = TRUE, paginationType = "jump", elementId = "leaflet-prov-summ" )
# Restore cache esp_set_cache_dir(initcache, verbose = TRUE)
if (!require("sessioninfo")) { install.packages("sessioninfo") } sessioninfo::session_info()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.