Problema al hacer el zoom a unos municipios con la funcion renderLeaflet

48 views
Skip to first unread message

Alejandro Ponce-mendoza

unread,
Aug 18, 2021, 11:22:36 AM8/18/21
to mxmaps

Hola Diego!!

Espero que estes muy bien...

 Estoy haciendo un Shiny con los datos de SADER y uso la función mxmunicipios_leaflet. me gustaría que al momento de seleccionar una serie de municipios (e.g. de aguascalientes) el mapa se hiciera un Zoom a estos...sin embargo no lo logro :(

 Aquí el mapa con todos los datos

 Screen Shot 2021-08-17 at 17.36.58.png

Cuando hago un filtro:

Screen Shot 2021-08-17 at 17.37.40.png 

No hace el Zoom hacia Aguascalientes en este caso :/

 Aquí como pido la función:

#############

 output$mymap2 <- renderLeaflet({
     
        MxMunicipios3 <- points1() %>%
          as.data.frame()
        HHH <- c("white",brewer.pal(6, "Reds"))
        pal <- colorNumeric(HHH, domain = MxMunicipios3$value)
        mxmunicipio_leaflet(MxMunicipios3,
                            pal,
                            ~ pal(value),
                            zoom = MxMunicipios3$region,
                            ~ sprintf("Estado: %s<br/> Municipio: %s<br/> Agricultores: %s<br/>Sup. apoyada (ha):  %s",
                                      state_name, municipio_name, Agricultor,value)) %>%
          addLegend(position = "topright", pal = pal, values = MxMunicipios3$value,
                    title = "Superficie<br>Sembrada (ha)") %>%
          addProviderTiles("CartoDB.Positron")
        
      })
    

##############

NOTA:

points1 = mi base de datos interactiva.

 Aqui mi sessionInfo()

#######

R version 4.1.0 (2021-05-18)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Big Sur 11.4

Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] RColorBrewer_1.1-2   xlsx_0.6.5           leaflet_2.0.4.1     
 [4] plotly_4.9.4.1       shinyWidgets_0.6.0   shinydashboard_0.7.1
 [7] patchwork_1.1.1      ghibli_0.3.2.9000    ggthemes_4.2.4      
[10] mxmaps_2020.1.0      openxlsx_4.2.4       readxl_1.3.1        
[13] forcats_0.5.1        stringr_1.4.0        dplyr_1.0.7         
[16] purrr_0.3.4          readr_1.4.0          tidyr_1.1.3         
[19] tibble_3.1.3         ggplot2_3.3.5        tidyverse_1.3.1     
[22] shiny_1.6.0          testthat_3.0.4       devtools_2.4.2      
[25] usethis_2.0.1      

 

########

 

Saludos

 

Alex

 

Diego Valle-Jones

unread,
Aug 18, 2021, 4:18:35 PM8/18/21
to mxmaps
Hola, hay un error en la función mxmunicipios_leaflet, puedes instalar la versión develop de mxmaps e intentar de nuevo

devtools::install_github('diegovalle/mxmaps@develop')

Alejandro Ponce-mendoza

unread,
Aug 18, 2021, 6:54:37 PM8/18/21
to mxmaps
Gracias Diego por responder tan pronto.

Se ve mucho mejor los estados con la función "opacity" y "fillOpacity". Aunque me hace un error a nivel estatal.... :/ usando el código que viene del ejemplo:

## Not run:
library(scales)
library(leaflet)
library(mxmaps)

data(df_mxstate)
df_mxstate$value <- df_mxstate$afromexican / df_mxstate$pop
pal1 <- colorNumeric("Blues", domain = df_mxstate$value)
mxstate_leaflet(df = df_mxstate,
                pal = pal1,
                pal(df_mxstate$value),
                fillOpacity = 0.8,
                mapzoom = 5,
                popup = sprintf("State: %s<br/>Value: %s",
                                df_mxstate$state_name, comma(df_mxstate$value))
                ) %>%
    addLegend(position = "bottomright", pal = pal, values = df_mxstate$value) %>%
    addProviderTiles("CartoDB.Positron")

## End(Not run)


###

me sale el siguiente error:

Error in FUN(X[[i]], ...) :
  argument "fillOpacity" is missing, with no default

Porqué será?

En cuanto al Zoom a nivel municipal todavía no lo logro hacer... te pego el código, no sin antes decirte que el problema de fillOpacity no se presenta en la función mxmunicipio_leaflet :) :)

Aquí el código:

####################

#Para el Zoom

datos_prueba <- df_mxmunicipio %>%
    as.data.frame() %>%
    filter(state_name == "Yucatán")

datos_prueba$value <- datos_prueba$indigenous /datos_prueba$pop

HHH <- c("white",brewer.pal(6, "Reds"))
pal <- colorNumeric(HHH, domain = datos_prueba$value)
#pal <- colorNumeric(magma, domain = datos_prueba$value)
mxmunicipio_leaflet(datos_prueba,
                    pal,
                    ~ pal(value),
                    opacity = 0.8,
                    fillOpacity = 0.8,
                    mapzoom = 6,
                    zoom = datos_prueba$region,
                    popup = sprintf("State: %s<br/>Municipio : %s<br/>Value: %s%%",
                                    datos_prueba$state_name,
                                    datos_prueba$municipio_name,
                                    round(datos_prueba$value * 100, 1))) %>%
    addLegend(position = "bottomright", pal = pal,
              values = datos_prueba$value) %>%
    addProviderTiles("CartoDB.Positron")


## End(Not run)



####################

Gracias por todo Diego

Diego Valle-Jones

unread,
Aug 19, 2021, 12:11:19 PM8/19/21
to mxmaps
Hola, si instalas la última versión de develop debe de hacer el zoom automático a los municipios seleccionados y funcionar con mxstate_leaflet

devtools::install_github('diegovalle/mxmaps@develop')

Si ocurre cualquier error no dudes en reportarlo

Alejandro Ponce-mendoza

unread,
Aug 20, 2021, 8:23:19 PM8/20/21
to mxmaps
Hola Diego...
Mil gracias... Hice una pequeña Shiny que te la comparto para que obtegas un par de Warnings que me impiden seguir... :/...

######Inicio de la Shiny #######


library(shiny)
library(leaflet)
library(mxmaps)
library(tidyverse)
library(RColorBrewer)

datos_prueba1 <- df_mxmunicipio %>%
    as.data.frame() %>%
    filter(state_name == "Oaxaca")


# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Mapa Prueba"),

    # Sidebar with a slider input for number of bins
    sidebarLayout(
        sidebarPanel(
            selectInput(
                inputId = "mun_estado",
                label = h6("Estado"),
                choices = c("Casi", "All", levels(as.factor(df_mxmunicipio$state_name)))
            )
        ),

        # Show a plot of the generated distribution
        fluidRow(leafletOutput(outputId = "mymap3"))
    )
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {
    
    points1 <- reactive({
        if(input$mun_estado != "All"){
            TTabla <- df_mxmunicipio %>%
                dplyr::filter(state_name %in% input$mun_estado) %>%
                distinct(region, .keep_all = T)    
        } else {
            TTabla <- df_mxmunicipio
        }
        
    })
    
    output$mymap3 <- renderLeaflet({
      
        datos_prueba <- points1() %>%
            as.data.frame() %>%
            mutate(value = indigenous / pop)
        
        HHH <- c("blue","white",brewer.pal(6, "Reds"))

        pal <- colorNumeric(HHH, domain = datos_prueba$value)
        
        mxmunicipio_leaflet(datos_prueba,
                            pal,
                            ~ pal(value),
                            opacity = 0.8,
                            fillOpacity = 0.8,
                            lng = -102,
                            lat = 23.8,
                            #mapzoom = 6,

                            zoom = datos_prueba$region,
                            popup = sprintf("State: %s<br/>Municipio : %s<br/>Value: %s%%",
                                            datos_prueba$state_name,
                                            datos_prueba$municipio_name,
                                            round(datos_prueba$value * 100, 1))) %>%
            addLegend(position = "bottomright", pal = pal,
                      values = datos_prueba$value) %>%
            addProviderTiles("CartoDB.Positron")
    })
}

# Run the application
shinyApp(ui = ui, server = server)


###### Fin de Shiny #########

Ahora ya logra hacer el Zoom sin problema... :) por ejemplo en Veracruz

Screen Shot 2021-08-20 at 19.07.55.png
Sin embargo hago un error con unos "warnings". Verás en el listado de estados que,  además de la palabra All, puse uno estado llamado Casi. Si seleccionas este estado ficticio me aparecen los siguientes warnings

Screen Shot 2021-08-20 at 19.10.30.png

lo de municipio y municipios no afecta y si aparecen los municipios. Pero el min(df_zoom$lat) y el de max... bloquean por completo mi Shiny... :/.

En leaflet cuando se tiene algo imposible de lograr sale el mapa mundi... algo como esto:

Screen Shot 2021-08-20 at 19.17.47.png

Muchas gracias por todo y espero que tu veas alguna solución a este tipo de problema.

Saludos

Alex

Diego Valle-Jones

unread,
Aug 22, 2021, 5:49:36 PM8/22/21
to mxmaps
Si no quieres que salga un error vas a tener que revisar que los municipios que le pases al argumento 'zoom' sean válidos. Por ejemplo, puedes agregarle un if a la parte de reactive para revisar que TTabla tenga más de un renglón
Reply all
Reply to author
Forward
0 new messages