library(leaflet)
library(dplyr)
munic <- esp_get_munic_siane(
year = "2025-01-01",
epsg = 4326,
moveCAN = FALSE,
rawcols = TRUE
) |>
# Get area in km2 from siane munic
# Already on the shapefile
mutate(area_km2 = st_area_sh * 10000)
# Get population
pop <- mapSpain::pobmun25 |>
select(-name)
# Paste
munic_pop <- munic |>
left_join(pop) |>
mutate(
dens = pob25 / area_km2,
dens_label = prettyNum(round(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>",
"(2025)</small>"
),
position = "bottomright"
)