How can I pass info from Leaflet popup to Shiny ou

2019-06-01 16:45发布

问题:

I have a Leaflet map (myMap) that I created from a shapefile and demographic data. The map displays the polygons (counties). When I run this map on its own - or when I render it from within Shiny - I can click on a county and the county ID is displayed in the popup that I created.

What I am stuck trying to figure out is how to access my popup values (ID) from within Shiny. For example, in my Shiny app I'd like to click on the county and have the county ID outputted to a text display or stored as a variable.

Here's the relevant code:

ui <- dashboardPage(
  dashboardBody(fluidRow(
    box(width = 9, status = "info", title = "CountyMap",
    leafletOutput("myMap"))
)

server <- function(input, output) {
  output$myMap <- renderLeaflet({map2})

  observe({
  event <- input$myMap_shape_click
  if (is.null(event))
  return()

  print(map2$county)  # I know that's not correct,
                      # but I want the county id from my leaflet popup!

  val <- map2$county  # Obviously not correct either, 
  })                  # but I would like to store this data

In case this helps, the Leaflet map that I call from Shiny (above) looks something like this, where "mapable" is a large spatial polygons data frame:

popup <- paste0("ID: ", mapable$countyID)

map2 <-leaflet() %>%
     addPolygons(data = mapable, 
                 popup = popup
     ) 

Any thoughts or pushes in the right direction would be greatly appreciated!

回答1:

Thanks to user5219763 for tipping me off to what the layerId argument is for! I went back to my leaflet map and added vectorized argument for layerID. In my case I created a vector of values from the "GEO_ID" column in the "large spatial polygons data frame" that I used for the map.

geoID <- as.vector(mapable$GEOID)

map2 <-leaflet() %>%
     addPolygons(data = mapable, 
                 layerId = geoID,
                 popup = popup
     )

When I run the shiny app and click on a polygon (county), I can test that the layerId is also being passed:

  observe({
    event <- input$myMap_shape_click
    if (is.null(event))
      return()
    print(event)      
  })


标签: r shiny leaflet