0

here is a dummy dataframe DF

Location <- c("A","B","C","D","E")
OwnBicycle <- c("Yes","Yes","Yes","No","No")
Latitude <- c(-0.091702,-3.218834,-2.856487,-1.300799,0.498922)
Longitude <- c(34.767958,40.116147,38.945562,36.785946,35.308054)
DF <- data.frame(Location,OwnBicycle,Latitude,Longitude)

loc <- unique(DF$Location)
ownbike <- unique(DF$OwnBicycle)

Part of Main Code on UI.

selectInput("loc", label = "Location", choices=loc, selected = "A")
leafletOutput("mymap", height = 500)

Server

# reactive for selectIpout
filtered <- reactive({
  DF[DF$Location == input$loc,]
})

#leafletProxy 
observe(leafletProxy("mymap", data = filtered()) %>%
          clearMarkers()%>%
          addMarkers(radius =3)
)

In leafletObserver on the Shiny dashboard, I'd like the map to zoom in to Location B,when a user selects Option B from selectInput. I tried Following steps highlighted here but for this it had a button which had the lat/lot already initialized?

Shree
  • 10,835
  • 1
  • 14
  • 36
andy
  • 1,947
  • 5
  • 27
  • 46

1 Answers1

4

You need to use flyTo with leafletProxy. You can adjust the zoom argument as per your needs. I have made some improvements to your code so it's slightly different from yours. -

library(shiny)
library(leaflet)

shinyApp(
  ui = fluidPage(
    selectInput("loc", label = "Location", choices=loc, selected = "A"),
    leafletOutput("mymap", height = 500)
  ),
  server = function(input, output) {
    filtered <- reactive({
      DF[DF$Location == input$loc,]
    })

    output$mymap <- renderLeaflet({
      leaflet() %>% addTiles()
    })

    mymap_proxy <- leafletProxy("mymap")

    observe({
      fdata <- filtered()
      mymap_proxy %>%
        clearMarkers() %>%
        addMarkers(lng = fdata$Longitude, lat = fdata$Latitude) %>%
        flyTo(lng = fdata$Longitude, lat = fdata$Latitude, zoom = 10)
    })
  }
)
Shree
  • 10,835
  • 1
  • 14
  • 36