1
votes

I'm working on leaflet with shiny. The tools is basic, i have a map with some markers (coming from a table with LONG and LAT).

What I want to do is to open a table or a graph when i click on the marker.

Is there a simple way to do it?

Do you have a really simple example: you have a maker on a map, you click on the marker, and there is a plot or a table or jpeg that s opening?

2
This is relatively simple. Please take a look at the following example: shiny.rstudio.com/gallery/superzip-example.html ; after that, you can check the code here: github.com/rstudio/shiny-examples/tree/master/… and specifically this js event handling file: github.com/rstudio/shiny-examples/blob/master/… - nilsole

2 Answers

5
votes

Here is another example, taken from here and a little bit adapted. When you click on a marker, the table below will change accordingly.

Apart from that, a good resource is this manual here: https://rstudio.github.io/leaflet/shiny.html

library(leaflet)
library(shiny)
myData <- data.frame(
  lat = c(54.406486, 53.406486),
  lng = c(-2.925284, -1.925284),
  id = c(1,2)
)
ui <- fluidPage(
  leafletOutput("map"),
  p(),
  tableOutput("myTable")
)
server <- shinyServer(function(input, output) {
  data <- reactiveValues(clickedMarker=NULL)
  # produce the basic leaflet map with single marker
  output$map <- renderLeaflet(
    leaflet() %>%
      addProviderTiles("CartoDB.Positron") %>%
      addCircleMarkers(lat = myData$lat, lng = myData$lng, layerId = myData$id)  
  )
  # observe the marker click info and print to console when it is changed.
  observeEvent(input$map_marker_click,{
    print("observed map_marker_click")
    data$clickedMarker <- input$map_marker_click
    print(data$clickedMarker)
    output$myTable <- renderTable({
      return(
        subset(myData,id == data$clickedMarker$id)
      )
    })
  })
})
shinyApp(ui, server)
1
votes

There is a leaflet example file here:

https://github.com/rstudio/shiny-examples/blob/ca20e6b3a6be9d5e75cfb2fcba12dd02384d49e3/063-superzip-example/server.R

 # When map is clicked, show a popup with city info
  observe({
    leafletProxy("map") %>% clearPopups()
    event <- input$map_shape_click
    if (is.null(event))
      return()

    isolate({
      showZipcodePopup(event$id, event$lat, event$lng)
    })
  })

Online demo (see what happens when you click on a bubble): http://shiny.rstudio.com/gallery/superzip-example.html

On the client side, whenever a click on a marker takes place, JavaScript takes this event and communicates with the Shiny server-side which can handle it as input$map_shape_click.