Gipuzkoa, una alternativa

Author

Diego Hernangómez

Published

November 30, 2023

Gipuzkoa

Servicio en https://b5m.gipuzkoa.eus/web5000/es/servicios-inspire/edificios.

Vamos a crear una BBDD local y usarla de base

Ejemplo de llamada

Parámetros mínimos de entrada

x <- c(-1.992148, 43.311305, -1.958436, 43.32748) # En 4326
verbose <- FALSE
cache_dir <- "alternativa"

Producto mínimo viable

Descarga y tratamiento de base de datos, la vamos a tratar y cachear. Mirar el sistema de cacheo de CatastRo: https://ropenspain.github.io/CatastRo/reference/index.html#cache-management

# Descarga del todo dataset si no tenemos la BBDD cacheada

cached_bbdd <- file.path(cache_dir, "ES.GFA.BU.gpkg")

is_cached <- file.exists(cached_bbdd)

if (isFALSE(is_cached)) {
  if (!dir.exists(cache_dir)) dir.create(cache_dir)

  # Descarga y trata
  bbdd_url <- "https://b5m.gipuzkoa.eus/inspire/download/GML/ES.GFA.BU.zip"
  destfile <- file.path(cache_dir, basename(bbdd_url))

  download.file(bbdd_url, destfile, quiet = !verbose)
  unzip(destfile, exdir = cache_dir, junkpaths = TRUE)

  # Lee la BBDD descargada y tratala para almacenarla
  bbdd_desc <- list.files(cache_dir, pattern = "BU.gml$", full.names = TRUE)

  bbdd_sf <- sf::st_read(bbdd_desc)

  # Hay columnas anidadas que dan problemas, de las vamos a eliminar
  # TODO: Profundizar
  the_df <- sf::st_drop_geometry(bbdd_sf)
  the_geom <- sf::st_geometry(bbdd_sf)
  unn <- vapply(the_df, class, FUN.VALUE = character(1))
  cols_are_list <- as.integer(which(unn == "list"))
  the_final_df <- the_df[, -cols_are_list]
  # The sf regenerated
  bbdd_sf <- sf::st_sf(the_final_df, geometry = the_geom)
  bbdd_sf <- sf::st_transform(bbdd_sf, 25830)

  # Y almacenamos la BBDD cacheada como gpkg
  sf::st_write(bbdd_sf, cached_bbdd, quiet = !verbose)
}

Y ahora hacemos la llamada sobre la BBDD cacheada

# El bbox necesitamos que esté en 25830
x_mod <- x
class(x_mod) <- "bbox"
x_mod <- sf::st_as_sfc(x_mod)
sf::st_crs(x_mod) <- sf::st_crs(4326)
x_poly_25830 <- sf::st_transform(x_mod, 25830)

# Query sobre la BBDD cacheada

x_sf <- sf::st_read(cached_bbdd,
  wkt_filter = sf::st_as_text(x_poly_25830),
  quiet = TRUE
)

x_sf <- sf::st_transform(x_sf, 25830)

Comprobación

library(ggplot2)

identical(sf::st_crs(x_poly_25830), sf::st_crs(x_sf))
#> [1] TRUE

ggplot() +
  geom_sf(data = x_poly_25830, aes(color = "BBOX"), fill = NA, linewidth = 2) +
  geom_sf(data = x_sf, aes(fill = "API Result")) +
  scale_colour_manual(values = "black") +
  labs(
    fill = "",
    color = ""
  )

Visualización

library(tidyverse)
buf <- sf::st_centroid(x_poly_25830) %>%
  sf::st_buffer(1000)

dataviz <- sf::st_intersection(x_sf, buf)

# Extract 4 initial positions
year <- substr(dataviz$dateOfConstruction.DateOfEvent.end, 1, 4)

# Replace all that doesn't look as a number with 0000
year[!(year %in% 0:2500)] <- "0000"

# To numeric
year <- pmax(1900, as.integer(year))


dataviz <- dataviz %>%
  mutate(
    year = year,
    year_cat = ggplot2::cut_width(year, width = 10)
  )

# Paleta
dataviz_pal <- hcl.colors(
  length(levels(dataviz$year_cat)),
  "Spectral"
)

ggplot(dataviz) +
  geom_sf(aes(fill = year_cat), color = NA) +
  scale_fill_manual(values = dataviz_pal) +
  theme_void() +
  labs(title = "Donostia/San Sebastián", fill = "") +
  theme(
    panel.background = element_rect(fill = "black"),
    plot.background = element_rect(fill = "black"),
    legend.justification = .5,
    legend.text = element_text(
      colour = "white",
      size = 12
    ),
    plot.title = element_text(
      colour = "white", hjust = .5,
      margin = margin(t = 30),
      size = 30
    ),
    plot.caption = element_text(
      colour = "white",
      margin = margin(b = 20), hjust = .5
    ),
    plot.margin = margin(r = 40, l = 40)
  )