[英]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.
我希望能够在Shiny / Leaflet地图上保存所有点击事件。 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
As you can see, I can print the click ids (or entire click event) when I click on a polygon. 如您所见,我可以在单击多边形时打印单击ID(或整个单击事件)。 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. 我看到有一个参数选项
autoDestroy = F
在observeEvent
,但我不知道我怎么会用它来保存以前单击多边形。 Is there a way that I can store ALL of my clicks/click$ids in a vector or list? 有没有办法可以存储我的所有点击/点击向量或列表中的$ ID?
You can do this using reactiveValues
to store the clicks. 您可以使用
reactiveValues
来存储点击。
Right at the top of your server function add 在服务器顶部添加功能
RV<-reactiveValues(Clicks=list())
and then change your observeEvent
to: 然后将
observeEvent
更改为:
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
. 每次点击都会发生什么,
id
会附加到RV$Clicks
存储的点击list
中。 This does not have to be a list
you could make it a vector
if that is better for you. 这不一定是一个
list
你可以把它作为一个vector
如果这对你更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.