Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

r - How to "save" click events in Leaflet Shiny map

What I want to do is pretty simple. I want to be able to save all click events on a Shiny/Leaflet map. Here's some example code:

library(raster)
library(shiny)
library(leaflet)

#load shapefile
rwa <- getData("GADM", country = "RWA", level = 1)

shinyApp(
  ui = fluidPage(
    leafletOutput("map")
  ), 

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

    #initial map output
    output$map <- renderLeaflet({
      leaflet() %>% 
        addTiles() %>% 
        addPolygons(data = rwa, 
                    fillColor = "white", 
                    fillOpacity = 1, 
                    color = "black", 
                    stroke = T, 
                    weight = 1, 
                    layerId = rwa@data$OBJECTID, 
                    group = "regions")
    }) #END RENDER LEAFLET

    observeEvent(input$map_shape_click, {

      #create object for clicked polygon
      click <- input$map_shape_click

      print(click$id)

    }) #END OBSERVE EVENT
  }) #END SHINYAPP

enter image description here

As you can see, I can print the click ids (or entire click event) when I click on a polygon. Easy enough. However, the moment I click another polygon, all information about my first clicked polygon is lost. I see that there is an argument option of autoDestroy = F in observeEvent, but I'm not sure how I would use this to save previously clicked polygons. Is there a way that I can store ALL of my clicks/click$ids in a vector or list?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this using reactiveValues to store the clicks.

Right at the top of your server function add

RV<-reactiveValues(Clicks=list())

and then change your observeEvent to:

observeEvent(input$map_shape_click, {

      #create object for clicked polygon
      click <- input$map_shape_click
      RV$Clicks<-c(RV$Clicks,click$id)
      print(RV$Clicks)

 }) #END OBSERVE EVENT

What happens is every time you click, the id is appended to the list of clicks stored in RV$Clicks. This does not have to be a list you could make it a vector if that is better for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...