如何“保存"Leaflet Shiny 地图中的点击事件 [英] How to "save" click events in Leaflet Shiny map
问题描述
我想做的很简单.我希望能够将所有点击事件保存在 Shiny/Leaflet 地图上.下面是一些示例代码:
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
如您所见,当我点击一个多边形时,我可以打印点击 ID(或整个点击事件).很容易.但是,当我单击另一个多边形时,有关我第一个单击的多边形的所有信息都会丢失.我看到 observeEvent
中有一个 autoDestroy = F
的参数选项,但我不确定如何使用它来保存以前单击的多边形.有没有一种方法可以将我的所有点击次数/click$ids 存储在向量或列表中?
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?
推荐答案
您可以使用 reactiveValues
来存储点击次数.
You can do this using reactiveValues
to store the clicks.
在你的服务器函数顶部添加
Right at the top of your server function add
RV<-reactiveValues(Clicks=list())
然后将您的 observeEvent
更改为:
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
每次点击时,id
都会附加到 RV$Clicks
中存储的点击的 list
中.这不一定是一个 list
你可以把它变成一个 vector
如果这对你更好.
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.
这篇关于如何“保存"Leaflet Shiny 地图中的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!