Leaflet map returns to its original configuration

2020-07-30 03:18发布

问题:

I configured my map to fit the size of my internet window. Unfortunately, when I change this size, my map returns to its basic configuration (setView for example), and my shapefile previously imported disappears. Is there a way to go beyond that?

    # server.R

#--------- ADD PACKAGES --------#
library(shiny)
library(shinydashboard)
library(leaflet)
library(rgdal)
library(rgeos)
library(shinyjs)
library(sp)
library(V8)
library(shinyalert)
library(leaflet.extras)
library(raster)

#--------- APPLICATION INSTRUCTIONS --------#
shinyServer(function(input, output, session){

  #--------- BOX CONTAINING THE MAP --------#
  output$ui <- renderUI( {
    req(input$box_height)

    box(height = paste0(input$box_height, "px"), width = 9,
        leafletOutput("map", height = input$box_height - 20)
    )
  })

  #--------- ADD LEAFLET MAP --------#
  output$map <- renderLeaflet({
    leaflet() %>%
      enableTileCaching() %>%
      addProviderTiles("Esri.WorldImagery", group = "Esri World Imagery", 
                options = providerTileOptions(minZoom = 2, maxZoom = 17), 
                tileOptions(useCache = TRUE, crossOrigin = TRUE)) %>%

      addTiles(group = "OSM", urlTemplate = "https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", 
               attribution = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', 
               options = providerTileOptions(minZoom = 2, maxZoom = 17), 
               tileOptions(useCache = TRUE, crossOrigin = TRUE)) %>%

      addMiniMap(toggleDisplay = T) %>%
      addScaleBar(position = 'bottomleft') %>%
      setView(lng = 97.963,lat = 20.380, zoom = 6 ) %>%
      addLayersControl(baseGroups = c("Esri World Imagery", "OSM"))
  })


  #-------- READ SHAPEFILE --------#
  #-------- SAVE IN TEMP FOLDER --------#
  #-------- CREATE A CSV --------#
  uploadShpfile <- reactive({
    if (!is.null(input$zip)) {
      zipFile <- input$zip
      zipPath <- substr(zipFile$datapath, 1, nchar(zipFile$datapath) - 5)
      unzip(zipFile$datapath, exdir = zipPath)
      pwd <- getwd()
      updir <- dirname(zipFile$datapath[1])
      setwd(updir)
      for (i in 1:nrow(zipFile)) {
        file.rename(zipFile$datapath[i], zipFile$name[i])
      }
      shpName <- zipFile$name[grep(zipFile$name, pattern = "*.shp")]
      shpPath <- paste(updir, shpName, sep = "/")
      setwd(updir)
      Layers <- ogrListLayers(shpPath)
      shpName <- readOGR(shpPath)
      shpName <- spTransform(shpName,CRS("+proj=longlat +datum=WGS84"))
      shapefile(shpName, paste(shpPath, Layers, "_WGS84.shp", sep = ""))
      write.table(paste(shpPath, Layers, "_WGS84.shp", sep = ""), 
                  file = "info_shp.csv", 
                  row.names = FALSE, 
                  col.names = FALSE, 
                  quote = FALSE)
      shpName
    }
  })


  #-------- ADD SHAPEFILE --------#
  observeEvent(input$zip, {
    data = uploadShpfile()
    map = leafletProxy("map")
    if (!is.null(uploadShpfile())){
      if(inherits(data, "SpatialPolygons")){
        shinyalert("Successful upload !", type = "info", timer = 2000)
        cent <- gCentroid(spgeom = uploadShpfile(), byid = FALSE)
        leafletProxy("map")%>%
          addPolygons(data = uploadShpfile(),
              stroke = TRUE,
              # color = "#00FFEC",
              # fillColor = "white",
              fillOpacity = 0.5)
      }

      if(inherits(data, "SpatialPoints")){
        shinyalert("Successful upload !", type = "info")
        cent <- gCentroid(spgeom = uploadShpfile(), byid = FALSE)
        leafletProxy("map") %>%
          addCircleMarkers(data = uploadShpfile(),
              stroke = TRUE,
              # color = "white",
              # fillColor = "#00FFEC",
              radius = 6,
              fillOpacity = 0.9)
      }
    }
  })
})


    # ui.R

#--------- ADD PACKAGES --------#
library(shiny)
library(shinydashboard)
library(leaflet)
library(rgdal)
library(rgeos)
library(shinyjs)
library(sp)
library(V8)
library(shinyalert)
library(leaflet.extras)
library(raster)

#--------- USER INTERFACE --------#
shinyUI(
  dashboardPage(
    dashboardHeader(title ="Sen2extract"),


    #--------- SIDEBAR CONFIGURATION --------#
    sidebar <- dashboardSidebar(
      sidebarMenu(
        menuItem("Map", tabName= "carte", icon = icon("globe")),
      ),

    #--------- ELEMENTS OF THE BODY --------#
    dashboardBody(


      #--------- CONFIGURE THE HEIGHT --------#
      tags$head(tags$script('
        // Set input$box_height when the connection is established
        $(document).on("shiny:connected", function(event) {
          var window_height = $(window).height();
          var header_height = $(".main-header").height();

          var boxHeight = window_height - header_height - 30;
          Shiny.onInputChange("box_height", boxHeight);
        });

        // Refresh the box height on every window resize event    
        $(window).on("resize", function(){
          var window_height = $(this).height();
          var header_height = $(".main-header").height();

          var boxHeight = window_height - header_height - 30;
          Shiny.onInputChange("box_height", boxHeight);
        });
      ')),
      # Boxes need to be put in a row (or column)


      tabItems(
        #--------- ELEMENTS TAB "carte" --------#
        tabItem(tabName ="carte",
                fluidRow(

                  box(
                    width = 3,
                    title = "Settings",
                    status = "primary",
                    solidHeader = TRUE,
                    collapsible = TRUE,
                    useShinyalert(),br(),
                    fileInput(inputId = "zip", label = "Upload your file (.zip) :", multiple = FALSE, accept = c('.zip')), 
                    checkboxGroupInput(inputId ="indice", label ="Choose a spectral index (multiple choice possible) :", choices = c("NDVI", "NDWIGAO", "NDWIMCF", "MNDWI")),br(),
                    dateRangeInput(inputId ="dates", label = "Select the date range :", start = "", end = ""), br(),
                    textInput(inputId = "mail", label = "Enter your email address :"), br(),br(),
                    shinyjs::useShinyjs(),
                    shinyjs::extendShinyjs(text = "shinyjs.reset = function() {window.location.reload(true)}"),
                    div(style = "display:inline-block", actionButton("reset_button", "Refresh", icon("refresh", lib ="glyphicon"))),
                    div(style = "display:inline-block", actionButton("send", "Send now !", icon("send", lib = "glyphicon"), style = "background-color : #000000 ; color : #fff ; border-color : #717878"))                 
                  ),

                  uiOutput("ui", width = "100%")
                )
        )  
      )
  )
)

On the first image, I imported a shapefile. If I change the size of the window (2nd image), the shapefile is no longer displayed (but we see it in the inputfile) and my map has returned to its original SetView.

标签: r shiny leaflet