rshinyr-leafletshiny-reactivity

Shiny dashboard and leaflet using selectInput


I am trying to use shiny dashboard with leaflet package. I tried using "SelectInput" function in the dashboard to create reactive map based on the input selected(geoArea). However, i am not able to make the leaflet and the SelectInput connect with each other.

I also wanted to distinguish two groups in my dataset and plot it in leaflet/shiny (column name "up.and.down" has positive and negative values).In Base R i could do it using filter option from the tidyverse package and give distinct colour to each but however i am not sure how this works in Shinydashboard.

library(shiny)
    library(shinydashboard)
    library(shinydashboardPlus)
    library(leaflet)
    library(tidyverse)


    
datafile<- read.csv("/Users/prabeshkc/Desktop/stackoverflow data.csv")

`ui<- dashboardPage(
  skin = "blue",
  dashboardHeader(title = "Cluster Map"),
  dashboardSidebar(
    selectInput("Area",label = "Geo Area",
                choices = datafile$geoArea)
  ),
  dashboardBody(
    fluidRow(box(width = 12,leafletOutput(outputId = "mymap")))
  ))`
    
`server <- function(input, output) {
 data_input<-reactive({
   datafile %>% 
     leaflet() %>% 
     addTiles() %>% 
     addMarkers(lng = datafile$lng,lat = datafile$lat)
 })
  data_input_ordered<-reactive({
    data_input()[order(match(data_input)$geoArea)]
  })`

  `labels<- reactive({
    paste("<p>", datafile$goals,"</p>"),
    paste("<p>", datafile$achieved,"</p>")
  })`
  
 `output$mymap<- renderLeaflet(
    datafile %>% 
      leaflet() %>% 
      addTiles() %>% 
      addCircleMarkers(lng = datafile$lng,lat = datafile$lat)
  )
}
 shinyApp(ui = ui, server = server)`

Solution

  • Try this one:

    library(shiny)
    library(shinydashboard)
    library(shinydashboardPlus)
    library(leaflet)
    library(tidyverse)
    
    
    datafile<-read.csv("/Users/prabeshkc/Desktop/stackoverflow data.csv") %>% 
      mutate(color=ifelse(up.and.down<0,"red","blue"))
    
    ui<- dashboardPage(
      skin = "blue",
      dashboardHeader(title = "Cluster Map"),
      dashboardSidebar(
        selectInput("Area",label = "Geo Area",
                    choices = datafile$geoArea)
      ),
      dashboardBody(
        fluidRow(box(width = 12,leafletOutput(outputId = "mymap")))
      ))
    
    server <- function(input, output) {
    
      output$mymap<- renderLeaflet({
        validate(need(datafile,"Add file"))
        validate(need(input$Area,"Select Area"))
        datafile %>% 
          filter(geoArea %in% input$Area) %>% 
          leaflet() %>% 
          addTiles() %>% 
          addCircleMarkers(lng = ~lng,lat = ~lat,color=~color,
                           popup = ~paste(paste0("Goals - ",goals),paste0("Achieved - ",achieved), sep="<br>"))
      })
    }
    shinyApp(ui = ui, server = server)