Creating maps with Leaflet Package and Rmd
Part of Course: Developing Data Products (Coursera - Johns Hopkins)
In this example, we created with Leaflet
package. Also, I used dplyr
for cleaning the data and widgetframe
for rendering in blogdown
correctly.
This map shows water allocations according to REPDA by CONAGUA in Yucatán Península, México, by September 2020. Coordinates are not validated
First step: Download and data cleaning
library(leaflet)
library(widgetframe)
library(htmlwidgets)
library(htmltools)
library(dplyr)
url <-"http://201.116.60.46/DatosAbiertos/Otorgamiento_de_Concesiones.zip"
temp <- tempfile()
temp2 <- tempfile()
download.file(url, temp, mode="wb")
unzip(zipfile = temp, exdir = temp2)
data <- read.csv(file = paste0(temp2,"\\CONCESIONES","\\ANEXOS_SUBTERRANEOS.csv",sep=""),encoding = "UTF-8")
data1 <- read.csv(file = paste0(temp2,"\\CONCESIONES","\\CONCESIONES.csv",sep=""),encoding = "UTF-8")
data$lat=data$GRADOS.LATITUD+((1/60)*data$MINUTOS.LATITUD)+((1/3600)*data$SEGUNDOS.LATITUD)
data$lng=((data$GRADOS.LONGITUD)+((1/60)*data$MINUTOS.LONGITUD)+((1/3600)*data$SEGUNDOS.LONGITUD))*-1
data_all <- merge(x = data,y= data1, by = "X.U.FEFF.TITULO", all.x = TRUE)
df <- filter(data_all, NOMBRE.DE.ESTADO %in% c("CAMPECHE","QUINTANA ROO","YUCATAN"),lat>=17.5,lat<=22,lng<=-87,lng>=-92) #filter by State and coordinates
df <- data.frame(lat=c(df$lat),lng=c(df$lng),uso=c(df$USO.QUE.AMPARA.EL.TITULO),vol=df$VOLUMEN.ANUAL.EN.m3)
unlink(c(temp, temp2))
pal <- colorFactor(c("cyan3","darkgreen","sienna","grey77","dodgerblue4",
"red4","tan4","darkslategrey","gold3"),df$uso) #Set colors
Second step: Generate the map with Leaflet package
Clusters count number of allocation in the region. Meanwhile, circles describe each concession by type and volume (a lot!, right?)
my_map <- leaflet() %>%
addTiles() %>% # It generate the main layer
addMarkers(lng=df$lng, lat=df$lat, popup = paste(df$uso,df$vol,"m3/year"),clusterOptions = markerClusterOptions()) %>% # Define marks
addCircles(lng=df$lng, lat=df$lat,weight = 1, radius = sqrt(df$vol) * 2, color=pal(df$uso)) %>%
addLegend(pal = pal,values = df$uso)%>%
frameWidget()
my_map %>%
frameWidget()
## Warning in frameWidget(.): Re-framing an already framed widget with new params
and… Why water allocation in the middle of the ocean? well… Some coordanates are wrong.