Reputation: 391
I have a simple shiny app that plots points from a csv file input. Currently, when I upload the file to the shiny app, the map doesn't do anything. I think this is because the leaflet map isn't reacting to the file being uploaded. How might I be able to fix this?
See my code below. Sample data can be found HERE.
library(shiny)
library(shinydashboard)
library(leaflet)
library(dplyr)
library(htmltools)
shinyApp(
ui <- fluidPage(
titlePanel("eBird Visualizer"),
fileInput("MyEBirdData_in", "MyEBirdData", buttonLabel = "Upload a .csv",
placeholder = "No File Selected...", width = "255px",
accept = ".csv"),
leafletOutput("myMap")
),
server = function(input, output) {
output$contents <- renderTable({
inFile <- input$MyEBirdData_in
if (is.null(inFile))
return(NULL)
myData = read.csv(inFile$datapath, header = input$header)
df0 = data.frame(myData$Submission.ID, myData$Latitude, myData$Longitude)
df = unique(df0)
names(df)[2] = 'latitude'
names(df)[3] = 'longitude'
})
output$myMap = renderLeaflet({
leaflet(data = df) %>% addProviderTiles(providers$CartoDB.Positron)
})
}
)
Upvotes: 1
Views: 835
Reputation: 25405
renderTable
is used to create a reactive table to be displayed in the UI. What you want is to have a variable that can be used in other reactive expressions to trigger them to update, in that case you should use reactive
or reactiveValue
, see for example here; 2/3 down the page, where they first introduce reactive
for a good example.
Also, you are currently referring to input$header
, which is not defined. Therefore you get an error when uploading the csv.
So you could do something like this:
library(shiny)
library(shinydashboard)
library(leaflet)
library(dplyr)
library(htmltools)
shinyApp(
ui <- fluidPage(
titlePanel("eBird Visualizer"),
fileInput("MyEBirdData_in", "MyEBirdData", buttonLabel = "Upload a .csv",
placeholder = "No File Selected...", width = "255px",
accept = c(".csv","text/csv")),
leafletOutput("myMap")
),
server = function(input, output) {
my_table <- reactive({
inFile <- input$MyEBirdData_in
if (is.null(inFile))
return(NULL)
myData = read.csv(inFile$datapath)
df0 = data.frame(myData$Submission.ID, myData$Latitude, myData$Longitude)
df = unique(df0)
names(df)[2] = 'latitude'
names(df)[3] = 'longitude'
print(df)
return(df)
})
output$myMap = renderLeaflet({
if(is.null(my_table()))
{
return(leaflet() %>% addProviderTiles(providers$CartoDB.Positron))
}
else
{
leaflet(data = my_table()) %>% addProviderTiles(providers$CartoDB.Positron) %>% addMarkers()
}
})
}
)
Upvotes: 3