1

I would like to create a button that would allow me to reset a fileinput, and delete the previously imported shapefile. Here is my code:

server.r:

library(shiny)
library(shinydashboard)
library(leaflet)
library(rgdal)
library(utf8)
library(sf)
library(rgeos)

shinyServer(function(input, output, session){


  # create reactive upload file function to store data
  uploadShpfile <- reactive({
    if (!is.null(input$shp)) {
      shpDF <- input$shp
      pwd <- getwd()
      updir <- dirname(shpDF$datapath[1])
      setwd(updir)
      for (i in 1:nrow(shpDF)) {
        file.rename(shpDF$datapath[i], shpDF$name[i])
      }
      shpName <- shpDF$name[grep(x = shpDF$name, pattern = "*.shp")]
      shpPath <- paste(updir, shpName, sep = "/")
      setwd(pwd)
      shpFile <- readOGR(shpPath)
      shpFile <- spTransform(shpFile,CRS("+proj=longlat +datum=NAD83 +no_defs +ellps=GRS80 +towgs84=0,0,0"))
    }
  })

  output$map <- renderLeaflet({

    leaflet() %>%
      addProviderTiles("Esri.WorldImagery", group = "Esri World Imagery", options = providerTileOptions(minZoom = 2, maxZoom = 17)) %>%
      addTiles(group = "OSM", options = providerTileOptions(minZoom = 2, maxZoom = 17)) %>%
      addMiniMap(toggleDisplay = T) %>%
      setView(lng = 97.963,lat = 20.380, zoom = 6 ) %>%
      addLayersControl(baseGroups = c("Esri World Imagery", "OSM"))
  })

  observeEvent(input$shp, {
    if (!is.null(uploadShpfile())) {
      cent <- gCentroid(spgeom = uploadShpfile(), byid = FALSE)
      leafletProxy("map") %>%
        addPolygons(data = uploadShpfile()) %>%
        setView(lat = slot(cent, "coords")[[2]], lng = slot(cent, "coords")[[1]], zoom = 7)
    }
  })
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.