rstudio / crosstalk

Inter-htmlwidget communication for R (with and without Shiny)
http://rstudio.github.io/crosstalk
Other
290 stars 53 forks source link

Automatically adjust zoom in leaflet map after filtering #107

Open gacolitti opened 3 years ago

gacolitti commented 3 years ago

Is it possible to reset the bounding box in leaflet map after filtering?

This is possible in a Shiny app like this:

library(shiny)
library(leaflet)

r_colors <- rgb(t(col2rgb(colors()) / 255))
names(r_colors) <- colors()

ui <- fluidPage(
  leafletOutput("mymap"),
  p(),
  actionButton("goButton", "New Points")
)

server <- function(input, output, session) {

  output$mymap <- renderLeaflet({
    leaflet() %>%
      addProviderTiles("Stamen.TonerLite",
                       options = providerTileOptions(noWrap = TRUE)
      )
  })

  observeEvent(input$goButton, {
    points <- data.frame("long" = rnorm(40) * 2 + 13, 
                            "lat" = rnorm(40) + 48)

    leafletProxy('mymap', session) %>%
      clearMarkers() %>%
      addMarkers(data = points) %>%
      fitBounds(lng1 = max(points$long),lat1 = max(points$lat),
                lng2 = min(points$long),lat2 = min(points$lat))

  })
}

shinyApp(ui, server)

I was sort of hoping this would work:

---
title: Fiji earthquakes
output: html_document
---

```{r}
library(crosstalk)
library(leaflet)
library(DT)

# Wrap data frame in SharedData
sd <- SharedData$new(quakes[sample(nrow(quakes), 100),])

# Create a filter input
filter_slider("mag", "Magnitude", sd, column=~mag, step=0.1, width=250)

# Use SharedData like a dataframe with Crosstalk-enabled widgets
bscols(
  leaflet(sd) %>% addTiles() %>% addMarkers() %>% fitBounds(
    lng1 = max(sd$data()$long),
    lat1 = max(sd$data()$lat),
    lng2 = min(sd$data()$long),
    lat2 = min(sd$data()$lat)
  ),
  datatable(sd, extensions="Scroller", style="bootstrap", class="compact", width="100%",
    options=list(deferRender=TRUE, scrollY=300, scroller=TRUE))
)