[Leaflet] Getting marker id when clicked inside the popup

2,024 views
Skip to first unread message

MySchizo Buddy

unread,
Sep 28, 2015, 11:34:32 AM9/28/15
to Shiny - Web Framework for R

In leaflet map I have markers with popup. When I click on a marker i can get the id of the marker via  input$map_marker_click$id. This works very well in Shiny.
I want to change this behavior and have a select button inside the popup which when clicked will give me the id of the marker.

Here is the working starting code. Save this to app.R and run it.

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
("locationid")
)

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>"))
 
})

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

  output$locationid
<- renderText({paste("Location Selected:", id())})
}

shinyApp
(ui, server)

Message has been deleted

MySchizo Buddy

unread,
Oct 4, 2015, 5:36:43 AM10/4/15
to Shiny - Web Framework for 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>", actionButton("selectlocation", "Select this Location", onclick = 'Shiny.onInputChange(\"button_click\",  Math.random())')))
 
})


  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$button_click, {
    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)



Reply all
Reply to author
Forward
0 new messages