Popups/modal in shiny with numeric input

I'm using numericInput in my shiny app, asking for lat/lng and then calculating the distance between the user input and a refenece point. I would like to have a warning if distance is bigger than a threshold :

library(shinyalert)
library(geosphere)
library(shiny)
ref =c(-3,51)
ui <- fluidPage(
  numericInput("lat", "lat:", NULL),
  numericInput("lng", "lng:", NULL),
  verbatimTextOutput("value")
)
server <- function(input, output) {
  
  dist <- reactive({
    if(!is.na(input$lat) && !is.na(input$lng) && input$lat <90 && input$lng <180 && input$lat > -90 && input$lng > -180){
      d = as.numeric(distm(c(input$lng,input$lat),ref,fun = distHaversine))}else{
        d= NA
      }
      
      result = list(d=d)
  })
  
  
  observeEvent(dist(),{
    if(!is.na(dist()$d) && as.numeric(dist()$d) > 50000){
      shinyalert("warning!", "out of boundry", type = "warning")
    }
  })
  output$value <- renderText({ dist()$d })
}
shinyApp(ui, server)

In my example, the observeEvent does not allow the input to be complete to give the warning popup ! let say if my input is 2 digit number , as soon as I put the fist digit it tries to calculate and if it does not satisfy the condition, it triggers the warning !
How I could change that ? I prefer not to use action bottom here , It is something that like we delay the observe event for some seconds that user finish with the input ?!

use shiny debounce feature. the help is at ?debounce

your code with a debounced reactive:

library(shinyalert)
library(geosphere)
library(shiny)
ref =c(-3,51)
ui <- fluidPage(
  numericInput("lat", "lat:", NULL),
  numericInput("lng", "lng:", NULL),
  verbatimTextOutput("value")
)
server <- function(input, output) {
  
  dist <- reactive({
    if(!is.na(input$lat) && !is.na(input$lng) && input$lat <90 && input$lng <180 && input$lat > -90 && input$lng > -180){
      d = as.numeric(distm(c(input$lng,input$lat),ref,fun = distHaversine))}else{
        d= NA
      }
    
    result = list(d=d)
  })
  dist_d <- dist %>% debounce(1000)
  
  observeEvent(dist_d(),{
    if(!is.na(dist_d()$d) && as.numeric(dist_d()$d) > 50000){
      shinyalert("warning!", "out of boundry", type = "warning")
    }
  })
  output$value <- renderText({ dist()$d })
}
shinyApp(ui, server)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.