Home > Mobile >  R Shiny - Add markers to leaflet map using file input
R Shiny - Add markers to leaflet map using file input

Time:10-13

I am attempting to add markers to a map based on coordinates uploaded by a user. I am having trouble storing the file input as a data frame and then passing the coordinates from the data frame to the proxy map to add markers.

ui <- fluidPage(
  
  titlePanel(title = "My Dashboard"),
  
  sidebarLayout(
      fileInput(inputId = "file",
                label = "File upload"),
      
    mainPanel(
      
      leafletOutput("mymap")
      
    )
  )
)

server <- function(input, output) {

  m <- leaflet() %>%
    setView(lng = -71.0589,
            lat = 42.3601,
            zoom = 12) %>%
    addProviderTiles(providers$CartoDB.Positron)

  output$mymap <- renderLeaflet(m)

    observe({
    input$file
    df <- read.csv('input$file$datapath')
    proxy <- leafletProxy("mymap", data = df)
    proxy %>% addMarkers(~long, ~lat)
  })

shinyApp(ui = ui, server = server)

CodePudding user response:

You were almost there, just change the way how you are reading the file to

observe({
   req(input$file)
   df <- read.csv(input$file$datapath)
   proxy <- leafletProxy("mymap", data = df)
   proxy %>% addMarkers(~long, ~lat)
})

That is removing the quotes '. The req makes sure that no error is thrown when there is no upload yet. When uploading a csv make sure that there are columns labeled long and lat.

  • Related