2

I am trying to mimic or figure out how a similar function as leafletProxy works in mapview package inside a Shiny app (flexdashboard). The idea is that I have a parameterized database query that fetches a sf dataset (~4200 polygons) based on user inputs and then plots in mapview. However, it appears that everytime this is done the entire map is redrawn?

Below is a reproducible example using the default franconia dataset and a shiny input to control the line opacity. I also include my code (commented out) to show an example of how it will be used as intended (i.e. to dynamically redraw a polygon layer based on a database fetch)

Is there a way in shiny to draw a "base" map of all the background maps stylings once and then only redraw the new polygon data as they are retrieved?

Thanks!


    ---
    title: "MRE"
    output: 
      flexdashboard::flex_dashboard:
        orientation: columns
        vertical_layout: fill
    runtime: shiny
    ---

    ```{r setup, include=FALSE}
    library(flexdashboard)
    library(mapview)
    library(shiny)
    library(leaflet)
    #library(RSQLite)
    #library(sf)
    ```


    Sidebar {.sidebar}
    -----------------------------------------------------------------------

    ```{r}
    # This is shiny input that will trigger entire map redraw
    sliderInput("gridlines", "Grid Line Opacity", 0, 1, 0, step = 0.1, ticks = FALSE)
    ```

    ```{r}
    ### THIS IS MY ACTUAL CODE...For reference

    # sp_grid <- reactive({
    #   db <- "../data/modeldata.db"
    #   con <- dbConnect(SQLite(), db )
    #   
    #   # set the sql based on user input
    #   sql <- 'SELECT id, Time,Cell_I, Cell_J, Cell_K, Cell_Botdepth_M, Zmax, Salinity, WKT_GEOMETRY 
    #                 FROM vwGridTK 
    #                 WHERE Time = :time 
    #                   AND Cell_K = :layer'
    #   
    #   df.grid <- dbGetQuery(con, sql, params = list(time = 0,
    #                                                layer = 1))
    #   dbDisconnect(con)
    #   
    #   st_as_sf(df.grid, wkt = "WKT_GEOMETRY") %>% st_set_crs(4326)
    #  
    # })

    ```

    Column {data-width=500}
    -----------------------------------------------------------------------

    ### Reproducible Example

NOTE the shiny input to control opacity

    ```{r}
    renderLeaflet({
      m <- mapview(franconia, zcol = "district", alpha = input$gridlines)
      m@map

    })

    ```

    Column {data-width=500}
    -----------------------------------------------------------------------

    ### My Example

    ```{r}

    # renderLeaflet({
    #     m <- mapview(sp_grid(), zcol = "Salinity",  
    #           legend = TRUE, alpha = input$gridlines)
    #   
    #   m@map
    # 
    # })
    ```
Phil
  • 7,287
  • 3
  • 36
  • 66
DarwinsBeard
  • 527
  • 4
  • 16

0 Answers0