问题描述
在一个闪亮的应用程序中使用 RStudio Leaflet 包,我已经能够实现所有我一直在寻找的功能,除了在单击标记对象后取消选择它.
Using the RStudio Leaflet package in a shiny app I've been able to achieve all the functionality I've looked for except deselecting a marker object once it has been clicked on.
更具体地说,input$map_click_id 值在单击任何标记之前设置为 NULL.单击标记后,将使用该标记的数据(ID、lat、lng、nonce)进行更新.我想设置地图,以便当用户点击地图上不是标记的任何区域时,input$map_click_id 将重置为 NULL,直到单击另一个标记.
More specifically, the input$map_click_id value is set to NULL before any markers are clicked. Upon clicking a marker it is updated with the data (ID, lat, lng, nonce) for that marker. I would like to set the map up so that when a user clicks on any area of the map which is not a marker, input$map_click_id is reset to NULL until another marker is clicked.
我已经尝试了许多解决方案来解决这个问题,例如比较标记点击和地图点击的点击时间,但是标记点击变量一旦设置为非 NULL 值,就会在每次点击地图时更新,不管它是否在标记上,所以这不起作用.
I've tried a number of work around solutions for this such as comparing the click times for marker clicks and map clicks, but the marker click variable, once set to a non-NULL value, is updated everytime the map is clicked, regardless of whether it is on a marker or not, so this doesn't work.
这里的任何帮助将不胜感激!下面是一个非常小的可重现示例.在这种情况下,我希望在单击时将标记信息打印到控制台,并在单击地图的任何非标记区域时将 NULL 返回到控制台.
Any help here would be greatly appreciated! Below is a very minimal reproducable example. In this case I would like for the marker info to print to the console when it is clicked, and for NULL to be returned to the console when any non-marker area of the map is clicked.
library(leaflet)
library(shiny)
# set basic ui
ui <- fluidPage(
leafletOutput("map")
)
server <- shinyServer(function(input, output) {
# produce the basic leaflet map with single marker
output$map <- renderLeaflet(
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addCircleMarkers(lat = 54.406486, lng = -2.925284)
)
# observe the marker click info and print to console when it is changed.
observeEvent(input$map_marker_click,
print(input$map_marker_click)
)
})
shinyApp(ui, server)
这似乎与 问的问题相同在这里,但由于没有答案,我想我会再试一次.
This appears to be the same question as asked here but as there was no answer for this, I thought I'd try again.
推荐答案
您可以使用 reactiveValues
来存储点击的标记,并在用户点击地图背景时重置它:
You could use a reactiveValues
to store the clicked marker and reset it whenever the user clicks on the map background:
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 = 54.406486, lng = -2.925284)
)
# observe the marker click info and print to console when it is changed.
observeEvent(input$map_marker_click,{
data$clickedMarker <- input$map_marker_click
print(data$clickedMarker)}
)
observeEvent(input$map_click,{
data$clickedMarker <- NULL
print(data$clickedMarker)})
})
这篇关于R Leaflet (CRAN) - 如何注册点击标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!