Ali Hadjihoseini
Ali Hadjihoseini

Reputation: 951

radioButtons in shiny app?

I have a radioButtons input with Yes and No :

radioButtons("rd", "3 rotor diameter circles:",list("Yes", "No"))

How should I modify my output in server.R, in a way that if the choice is YES, it consider the addCircles command and if is No ignore that line ?

output$mymap <- renderLeaflet({
    infile=input$File
    if (is.null(infile))
      return(NULL)

    df.20 <-  Coor1
    getColor <- function(Layout) {
      sapply(Layout$j1, function(j1) {
        if(j1 < 1) {
          "red"
        } else {
          "green"
        } })
    }

    icons <- awesomeIcons(
      spin=TRUE,

      icon = 'star',
      iconColor = 'lightgray',
      library = 'fa',
      markerColor = getColor(df.20)
    )

    leaflet() %>% 
      addProviderTiles("OpenTopoMap", group = "MapQuestOpen.Aerial") %>%
      addAwesomeMarkers(data = df.20,~long, ~lat, icon=icons, popup = ~as.character(mag), label = ~as.character(Name))%>%
      addCircles(data = df.20,lng=~long, lat=~lat,radius=~rad,weight = 1,fill = FALSE)%>%
      addMeasure(primaryLengthUnit='meters',primaryAreaUnit='sqmeters')
  })

Upvotes: 1

Views: 3359

Answers (2)

Victorp
Victorp

Reputation: 13856

You should use leaflet's proxy method to do that, and add/remove circles in an observer, consider this example :

library("shiny")
library("leaflet")

df.20 <- quakes[1:20,]

ui <- fluidPage(

  radioButtons(inputId = "add_circles", label = "Add circles", choices = c("Yes", "No")),

  leafletOutput(outputId = "mymap")

)

server <- function(input, output, session) {

  # your initial map
  output$mymap <- renderLeaflet({
    leaflet(df.20) %>% addTiles() %>% addCircles()
  })

  # add or remove circles when clicking the radio button
  observeEvent(input$add_circles, {
    if (input$add_circles == "Yes") {
      leafletProxy(mapId = "mymap", data = df.20) %>% addCircles()
    } else if (input$add_circles == "No") {
      leafletProxy(mapId = "mymap") %>% clearShapes()
    }
  }, ignoreInit = TRUE)
}

shinyApp(ui = ui, server = server)

Look at https://rstudio.github.io/leaflet/shiny.html

Note : here I used clearShapes, it remove also polygons, rectangles and polylines, you can remove only circles by defining layerId in addCircles and use removeShape.

Upvotes: 2

Mal_a
Mal_a

Reputation: 3760

You could try this:

leaflet() %>% 
  addProviderTiles("OpenTopoMap", group = "MapQuestOpen.Aerial") %>%
  addAwesomeMarkers(data = df.20,~long, ~lat, icon=icons, popup = ~as.character(mag), label = ~as.character(Name))%>%
  {if(input$rd == "Yes")addCircles(data = df.20,lng=~long, lat=~lat,radius=~rad,weight = 1,fill = FALSE)}%>%
  addMeasure(primaryLengthUnit='meters',primaryAreaUnit='sqmeters')

i have used if statement inside of the leaflet code, saying that if input$rd == "Yes", then addCircles(...) should be considered.

Upvotes: 0

Related Questions