Limpiar la memoria de R.
rm(list=ls())
Cargar las librerias previamente instaladas en la consola.
library(rasterVis)
library(raster)
library(terra)
library(rgeos)
library(rgdal)
library(elevatr)
library(sf)
library(tidyverse)
library(mapview)
library(ggplot2)
library(leaflet)
library(tmap)
library(RColorBrewer)
LOs datos de elevación son usados en gran cantidad de aplicaciones, incluyendo visualizacion, hidrologia y el modelo ecologico. El paquete “elevatr” funciona para estandarizar el acceso a los datos de elevación desde la web APIs. Durante el desarrollo del siguiente cuaderno, se obtendran tanto mapas estáticos como interactivos, los cuales reflejarán los municipios del departamento del meta con sus respectivas elevaciones y tipos de pendiente.
Primero, se carga un shapefile o un geopackage que represente los municipios del departamento que se esta trabajando, en este caso el Meta. En este cuaderno, se usará un geopackage, el cual fue descargado como shapefile originalmente. Sin embargo, este archivo abarcaba todos los municipios de Colombia, por lo que se recortó por medio del programa Qgis para obtener solo los municipios del departamento del Meta. Mediante este archivo, se crea un objeto, el cual sera llamado “munic”.
munic <- st_read("C:/GB2/CUADERNO_3/CUADERNO_3/MUNI_META.gpkg")
## Reading layer `MUNI_META' from data source
## `C:\GB2\CUADERNO_3\CUADERNO_3\MUNI_META.gpkg' using driver `GPKG'
## Simple feature collection with 29 features and 10 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -74.89921 ymin: 1.604238 xmax: -71.07753 ymax: 4.899101
## Geodetic CRS: MAGNA-SIRGAS
Se revisa la geometria, las coordenadas, CRS y los atributos del objeto “munic”.
head(munic)
## Simple feature collection with 6 features and 10 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -74.39891 ymin: 3.704314 xmax: -72.73891 ymax: 4.736325
## Geodetic CRS: MAGNA-SIRGAS
## DPTO_CCDGO MPIO_CCDGO MPIO_CNMBR MPIO_CDPMP VERSION AREA
## 1 50 001 VILLAVICENCIO 50001 2018 1285879354
## 2 50 006 ACACÃ\u008dAS 50006 2018 1123737929
## 3 50 110 BARRANCA DE UPÃ\u008dA 50110 2018 403818863
## 4 50 124 CABUYARO 50124 2018 913662509
## 5 50 150 CASTILLA LA NUEVA 50150 2018 514685967
## 6 50 223 CUBARRAL 50223 2018 1157865246
## LATITUD LONGITUD Shape_Leng Shape_Area geom
## 1 4.091669 -73.49292 2.039775 0.10471406 MULTIPOLYGON (((-73.69288 4...
## 2 4.009644 -73.72391 2.074207 0.09150745 MULTIPOLYGON (((-73.80268 4...
## 3 4.519076 -72.99549 1.312018 0.03289441 MULTIPOLYGON (((-73.01607 4...
## 4 4.315245 -72.95269 2.008848 0.07440326 MULTIPOLYGON (((-73.08865 4...
## 5 3.805154 -73.53887 1.349329 0.04189962 MULTIPOLYGON (((-73.7252 3....
## 6 3.828242 -74.07530 2.075091 0.09426999 MULTIPOLYGON (((-74.20143 4...
El siguiente paso es crear un nuevo objeto con los centroides de los municipios, el cual se llamará “centers”. El objetivo es encontrar un punto central para cada región.
sp.munic = as_Spatial(munic)
centers <- data.frame(gCentroid(sp.munic, byid = TRUE))
centers$region <- row.names(sp.munic)
centers$munic <- sp.munic$MPIO_CNMBR
Tabla de atributos del nuevo objeto creado “centers”.
centers
## x y region munic
## 1 -73.49292 4.091669 1 VILLAVICENCIO
## 2 -73.72391 4.009644 2 ACACÃ\u008dAS
## 3 -72.99549 4.519076 3 BARRANCA DE UPÃ\u008dA
## 4 -72.95269 4.315245 4 CABUYARO
## 5 -73.53887 3.805154 5 CASTILLA LA NUEVA
## 6 -74.07530 3.828242 6 CUBARRAL
## 7 -73.31478 4.232526 7 CUMARAL
## 8 -73.71442 4.353770 8 EL CALVARIO
## 9 -73.88801 3.615625 9 EL CASTILLO
## 10 -73.83162 3.706970 10 EL DORADO
## 11 -73.59625 3.382370 11 FUENTE DE ORO
## 12 -73.74696 3.496563 12 GRANADA
## 13 -73.95984 3.947776 13 GUAMAL
## 14 -74.12455 3.154771 14 MESETAS
## 15 -74.43066 3.047727 15 URIBE
## 16 -74.09628 3.614715 16 LEJANÃ\u008dAS
## 17 -72.72109 2.752260 17 PUERTO CONCORDIA
## 18 -72.64570 4.014299 18 PUERTO LÓPEZ
## 19 -73.23671 3.193093 19 PUERTO LLERAS
## 20 -73.13780 2.758084 20 PUERTO RICO
## 21 -73.47367 4.237467 21 RESTREPO
## 22 -73.27583 3.847617 22 SAN CARLOS DE GUAROA
## 23 -73.81635 3.289851 23 SAN JUAN DE ARAMA
## 24 -73.66041 4.471346 24 SAN JUANITO
## 25 -72.98537 3.535909 25 SAN MARTÃ\u008dN
## 26 -73.66652 2.811617 26 VISTAHERMOSA
## 27 -74.09488 2.161864 27 LA MACARENA
## 28 -71.93806 3.117523 28 MAPIRIPÃ\u0081N
## 29 -71.63157 4.005034 29 PUERTO GAITÃ\u0081N
# z denotes the zoom level of the data
# the higher the zoom the higher the spatial resolution
#elevation <- get_elev_raster(munic, z = 12)
elevation <- get_elev_raster(munic, z = 10)
## Mosaicing & Projecting
## Note: Elevation units are in meters.

elevation
## class : RasterLayer
## dimensions : 5115, 6148, 31447020 (nrow, ncol, ncell)
## resolution : 0.0006861734, 0.0006861734 (x, y)
## extent : -75.23438, -71.01578, 1.406056, 4.915833 (xmin, xmax, ymin, ymax)
## crs : +proj=longlat +ellps=GRS80 +no_defs
## source : file2fe469c25d87.tif
## names : file2fe469c25d87
# uncomment if needed
# write to geotiff file (depends on rgdal)
# NOTE THAT z10 means Zoom Level 10
# CHANGE IT IF NEEDED
#if (require(rgdal)) {
rf <- writeRaster(elevation, filename=file.path("C:/GB2/CUADERNO_3/CUADERNO_3/META_dem_z10.tif"), format="GTiff", overwrite=TRUE)
#}
se guarda el archivo en el directorio de trabajo.
(elevation = raster("C:/GB2/CUADERNO_3/CUADERNO_3/META_dem_z10.tif"))
## class : RasterLayer
## dimensions : 5115, 6148, 31447020 (nrow, ncol, ncell)
## resolution : 0.0006861734, 0.0006861734 (x, y)
## extent : -75.23438, -71.01578, 1.406056, 4.915833 (xmin, xmax, ymin, ymax)
## crs : +proj=longlat +ellps=GRS80 +no_defs
## source : META_dem_z10.tif
## names : META_dem_z10
## values : -838, 4359 (min, max)
El siguente paso es visualizar los datos de elevacion y se van a convertir en un nuevo objeto, el cual se llamará “elevation2”.
#Use it only when zoom data was very high
elevation2 <- aggregate(elevation, fact=4, fun=mean)
crs(elevation2) <- "+proj=longlat +datum=WGS84"
Para una buena visualización, se debe tener una buena paleta de colores. En este caso se usara la siguiente:
pal <- colorNumeric(c("forestgreen","lawngreen","tan","white"), values(elevation2),
na.color = "transparent")
Ahora, con la libreria “leaflet” se pueden ver los datos de elvación:
leaflet(munic) %>% addTiles() %>%
addPolygons(color = "white", weight = 1.0, smoothFactor = 0.5,
opacity = 0.25, fillOpacity = 0.15,
popup = paste("Region: ", munic$MPIO_CNMBR, "<br>",
"Km2: ", munic$MPIO_NAREA, "<br>")) %>%
addLabelOnlyMarkers(data = centers,
lng = ~x, lat = ~y, label = ~region,
labelOptions = labelOptions(noHide = TRUE, direction = 'top', textOnly = TRUE)) %>%
addRasterImage(elevation2, colors = pal, opacity = 0.9) %>%
addLegend(pal = pal, values = values(elevation2),
title = "Datos de Elevacion para el Meta (mts)")