library(shiny)
library(leaflet)
library(leaflet.providers)
ui <- fluidPage(
leafletOutput('map',width = "1331",height = "400"))
server <- function(input, output, session){
output$map <- renderLeaflet({
m<-leaflet() %>%
addProviderTiles(providers$OpenStreetMap,
options = providerTileOptions(noWrap = TRUE))%>%
setView(lng =-73.935242, lat =40.730610, zoom= 12)})
observe({ click = input$map_click
if(is.null(click))
return()
else
clicks=data.frame(click[1:2])
leafletProxy("map") %>%
addMarkers(data = clicks) #Adds a marker on each click
clicklist <<- reactiveVal(list()) # empty list
observeEvent(input$map_click, {
click <- input$map_click
temp <<- clicklist() # get the list of past clicks
temp[[length(temp)+1]] <<- click[1:2] # add this click to the list
clicklist(temp)
print(clicklist)}) #show on the console lat and lng
})
}
shinyApp(ui = ui, server = server)
an image to attract your attention
Console:
reactiveVal: [1] "40.74778, -73.97953"
reactiveVal: [1] "40.73191, -73.99704"
reactiveVal: [1] "40.73191, -73.99704" "40.73191, -73.99704"
The code above saves only the last user click on the map in the "clicklist" object, and repeats it as many times as the user clicks on the map.
>clicklist
reactiveVal: [1] "40.72931, -73.99326" "40.72931, -73.99326" "40.72931, -73.99326"
The object class is reactivevalue.
> class(clicklist)
[1] "reactiveVal" "reactive"
How to save each click and access them individually?
Expected output
>clicklist
[[1]]
[1]40.74778 -73.97953
[[2]]
[1]40.73191 -73.99704
>clicklist[1]
[1] 40.74778, -73.97953
>clicklist[1][[1]][1]
[1] 40.74778
>clicklist[1][[1]][2]
-73.97953
>clicklist[2]
[[1]]
[1] 40.73191 -73.99704
>clicklist[2][[1]][1]
[1] 40.73191
> clicklist[2][[1]][2]
[1] -73.99704