submit button in leaflet popup doesn't trigger

2019-08-12 09:41发布

问题:

I need a workaround for this problem. I have a submit button inside a popup. When I click on the marker, the input$map_marker_click$id now contains the id of the marker clicked.

There is a submit button in the popup. When the submit button is clicked I want to save the input$map_marker_click$id to a variable. Using oberserveEvent or eventReactive both are not working for me.

Here is the code save it as app.R

library(shiny)
library(leaflet)

df <- data.frame("id" = c("1", "2"),
                 "lng" = c(-93.65, -93.655),
                 "lat" = c(42.0285, 42.03),
                 "Text" = c("Department of Statistics", "something else"))


ui <- fluidPage(
  leafletOutput("map"),
  textOutput("locationid1"),
  textOutput("locationid2")
)

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

  output$map <- renderLeaflet({
    df %>% leaflet() %>%
      addProviderTiles("CartoDB.Positron") %>%
      setView(-93.65, 42.0285, zoom = 15) %>%
      addMarkers(layerId = ~id, popup = ~paste("<b>", Text, "</b></br>
                                               <button id='selectlocation' type='button' class='btn btn-default action-button'>Select Location</button>"))
  })


  id1 <- reactive({
     validate(
       need(!is.null(input$map_marker_click), "Please select a location from the map above")
     )
    input$map_marker_click$id
  })

  id2 <- eventReactive(input$selectlocation, {
    input$map_marker_click$id
  })


  output$locationid1 <- renderText({paste("Location Selected using marker click:", id1())})
  output$locationid2 <- renderText({paste("Location Selected using popup select button click:", id2())})

}

shinyApp(ui, server)

回答1:

The issue might be that Shiny does not know you are adding buttons and so there are no bindings.

A dirty trick could be to add an onclick function to the buttons that tells Shiny it has been clicked:

For ex:

<button onclick='Shiny.onInputChange(\"button_click\",  Math.random())' id='selectlocation' type='button' class='btn btn-default action-button'>Select Location</button>

This JS function will send the random number to Shiny, and you can access it in server.R using input$button_click.

You can then use input$button_click in your eventReactive

The proper way to do this is probably to use Shiny.unbindAll() and Shiny.bindAll() see here at the bottom, but I'm not sure how to do that here.



标签: r shiny leaflet