Reputation: 981
I am building a shiny application which contains a leaflet map with markers on it, and a table with information about each marker next to it. As I zoom in the leaflet map, how would I update the table to only show markers still visible on the leaflet map?
# Minimum Viable Example
library(shiny)
library(leaflet)
library(DT)
data(quakes)
# Define UI
ui <- fluidPage(
# leaflet box
column(
leafletOutput("mymap"),
width = 8
),
#data table box
column(
DT::dataTableOutput("table"),
width = 4
)
)
# Define server logic
server <- function(input, output) {
# leaflet map
output$mymap <- renderLeaflet({
# Show first 20 rows from the `quakes` dataset
leaflet(data = quakes[1:20,]) %>% addTiles() %>%
addMarkers(~long, ~lat, popup = ~as.character(mag), label = ~as.character(mag))
})
# data table
output$table = DT::renderDataTable({
quakes
})
}
# Run the application
shinyApp(ui = ui, server = server)
Upvotes: 1
Views: 641
Reputation: 3388
Use the input$mymap_bounds
event to filter the data. In your example, add library(dplyr)
and change output$table
to
output$table = DT::renderDataTable({
if (isTruthy(input$mymap_bounds)) {
bounds = input$mymap_bounds
quakes %>% filter(
between(long, bounds$west, bounds$east),
between(lat, bounds$south, bounds$north)
)
} else
quakes
})
Note that this filters the entire quakes
table, not the 20 items you show. Modify to suit. See the Events section of this page for details:
https://rstudio.github.io/leaflet/shiny.html
Upvotes: 1