I was thinking that it 'double plots' because of invalid combinations, which can be skipped.
library(shiny)
library(leaflet)
library(tidyverse)
(myoptions <- tibble(which=c("x","x","y","y"),
colour=c("red","blue","red","yellow")))
dlat <- 1 / 111000 * 100 # degrees per metre
n <- 10000 # number of circles
mylng <- 175.322 + (runif(n) * 2 - 1) * dlat * 6
mylat <- -37.789 + (runif(n) * 2 - 1) * dlat * 1.5
ui <- fluidRow(
tags$h2("Avoid double reaction in leaflet"),
leafletOutput("map"),
selectInput("which", label = "Axis to collapse", choices = c("x","y")),
selectInput("colour", label = "Choose colour", choices = filter(myoptions,
which == "x") %>%
pull(colour))
)
server <- function(input, output, session) {
observeEvent(input$which, {
# colour choices are dependent on input$which
if (input$which == "x"){
updateSelectInput(session, "colour",
label = "Choose colour",
choices = filter(myoptions,
which == "x") %>%
pull(colour))
} else {
updateSelectInput(session, "colour",
label = "Choose colour",
choices = filter(myoptions,
which == "y") %>%
pull(colour))
}
})
makepoints <- reactive({
# data is dependent on input$which
if (input$which == "x"){
x <- mylng
y <- -37.789 + (mylat - -37.789) / 10
} else {
x <- 175.322 + (mylng - 175.322) / 10
y <- mylat
}
list(x = x, y = y)
})
output$map <- renderLeaflet({
cat("renderLeaflet\n")
leaflet() %>%
addTiles() %>%
setView(175.322, -37.789, zoom = 17)
})
observe({
# plot is dependent on data and also on colour, so triggers twice
if(filter(myoptions,
which==input$which,
colour==input$colour) %>% nrow() >0 ) {
cat(paste("replot", input$which, input$colour, "\n"))
leafletProxy("map") %>%
clearShapes() %>%
addCircles(
lng = makepoints()$x,
lat = makepoints()$y,
radius = 1,
color = input$colour)
}
else {
cat("skipping invalid combo ",input$which," ",input$colour,"\n")
}})
}
shinyApp(ui = ui, server = server)