-1

I want to present a leaflet map inside a tabpanel in Shiny. The problem, however, is that the data point circles don't render ininitially. Only after I move the slider the circles show up on the map. Is it possible to show the circles when I click on the tabpanel?

Here is an example using the quakes data.

library(shiny)
library(leaflet)

ui <- navbarPage("Shiny app",
                 tabPanel("Empty"),
                 navbarMenu("Quakes",
                            tabPanel("Quakes map",
                                     bootstrapPage(
                                       sidebarLayout(
                                         sidebarPanel(top = 10, right = 10,
                                                      sliderInput("range", "Magnitudes", min(quakes$mag), max(quakes$mag),
                                                                  value = range(quakes$mag), step = 0.1)
                                         ),
                                         mainPanel(
                                           leafletOutput("map")
                                         )
                                       )
                                     )
                            )
                 )
)

server <- function(input, output, session) {
  
  filteredData <- reactive({
    quakes[quakes$mag >= input$range[1] & quakes$mag <= input$range[2],]
  })
  
  
  output$map <- renderLeaflet({
    leaflet(quakes) %>% addTiles() %>%
      fitBounds(~min(long), ~min(lat), ~max(long), ~max(lat))
  })
  
  observe({
    
    leafletProxy("map", data = filteredData()) %>%
      clearShapes() %>%
      addCircles(radius = ~10^mag/10, weight = 1, color = "#777777",
                 fillOpacity = 0.7, popup = ~paste(mag)
      )
  })
  
}

shinyApp(ui, server)
johnny
  • 423
  • 3
  • 10
  • 1
    does this help ? https://stackoverflow.com/questions/62700258/leaflet-in-another-tab-not-updated-with-leafletproxy-before-visiting-tab – gdevaux Apr 04 '22 at 06:57
  • 1
    omg I have been hovering around on that page many times but I missed a vital part (the dependency). thanks for making be go back to the question again. I made it work. I vote to close this question. – johnny Apr 04 '22 at 07:28

1 Answers1

-1

There's no reason to use output$map and a proxy just to use the reactive data (or maybe I missed something). You can simply use filteredData() in your original renderLeaflet():

server <- function(input, output, session) {
  
  filteredData <- reactive({
    quakes[quakes$mag >= input$range[1] & quakes$mag <= input$range[2],]
  })
  

  output$map <- renderLeaflet({
    leaflet(filteredData()) %>% addTiles() %>%
      fitBounds(~min(long), ~min(lat), ~max(long), ~max(lat)) %>% 
      addCircles(radius = ~10^mag/10, weight = 1, color = "#777777",
                 fillOpacity = 0.7, popup = ~paste(mag)
      )
  })
  
}
bretauv
  • 7,756
  • 2
  • 20
  • 57