【问题标题】:How do I save addDrawToolbar shapes drawn in an R Leaflet Shiny map so I can re-import them?如何保存在 R Leaflet Shiny 地图中绘制的 addDrawToolbar 形状,以便重新导入它们?
【发布时间】:2020-12-17 20:11:32
【问题描述】:

我需要使用leaflet.extras 中的addDrawToolbar 在 R Leaflet Shiny 应用程序 中绘制形状,并将它们保存到可以由 R Leaflet 重新导入的文件中闪亮的应用稍后。

我关注的是 Bhaskar Karambelkar 在GitHub 中的leaflet.extras 信息,其中列出了为绘制的形状提取数据的命令。如何在 R 中解析出这些数据?

以下代码是我目前能做的:绘制形状并将它们打印为.csv 或.txt 文件。我已经包括了这两个例子。因此,在这段代码中,您从绘图工具栏中绘制任何您想要的形状,然后点击Generate Shape List 按钮。

它适用于捕获所有形状坐标,但在这些格式中,数据并不像我需要的那样有用。有没有办法解析这些数据,以便在需要时重新导入、显示和编辑?非常感谢您对此的任何见解!

library(shiny)
library(leaflet)
library(leaflet.extras)
library(utils)

sh <- data.frame()

ui <- bootstrapPage(
    tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
    leafletOutput("mymap", width = "100%", height = "100%"),
    absolutePanel(top = 10, right = 10, width = 300,
                  style = "padding: 8px",
                  actionButton("printShapes", h5(strong("Generate Shape List")))
    )
)

server <- function(input, output, session) {
    
    output$mymap <- renderLeaflet({
        leaflet() %>%
            addTiles(group = "Default", attribution = 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors') %>%
            setView(lng = -98, lat = 38, zoom = 4) %>%
            addDrawToolbar(targetGroup = "draw", position = "topleft", editOptions = editToolbarOptions(edit=TRUE))
    })
    
    # Generate Shape List Action Button
    observeEvent(input$printShapes, {
        shapedf <- data.frame()
        reactive(shapedf)                       
        shapedf <-input$mymap_draw_all_features  
        sh <<- as.data.frame(shapedf)           
        sh <- t(sh)                             
        shpwrite <- write.csv(sh, paste0("OUTPUTdrawings",".csv"))
        shpwrite1 <- dput(sh, file = "OUTPUTdrawings1.txt")
    })
}

shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny leaflet


    【解决方案1】:

    经过深思熟虑、焦虑、反复试验,我终于想出了如何做到这一点。不确定这是否是最好的方法,但它确实有效。

    library(shiny)
    library(leaflet)
    library(leaflet.extras)
    library(utils)
    
    sh <- data.frame()
    
    ui <- bootstrapPage(
        tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
        leafletOutput("mymap", width = "100%", height = "100%"),
        absolutePanel(top = 10, right = 10, width = 300,
                      style = "padding: 8px",
                      fileInput("drawingFile",h4(strong("Input Drawing CSV")), accept = ".csv"),
                      actionButton("printShapes", h5(strong("Generate Drawing File")))
        )
    )
    
    server <- function(input, output, session) {
        
        output$mymap <- renderLeaflet({
            leaflet() %>%
                addTiles(group = "Default", attribution = 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors') %>%
                setView(lng = -98, lat = 30, zoom = 4) %>%
                addDrawToolbar(targetGroup = "draw", position = "topleft", editOptions = editToolbarOptions(edit=TRUE))
        })
        
        # Generate Shape List Action Button
        observeEvent(input$printShapes, {
            shapedf <- data.frame()
            reactive(shapedf)
            shapedf <-input$mymap_draw_all_features
            sh <<- as.data.frame(shapedf)
            
            # sh <- t(sh) # This is easier to read manually, but not for reading into R.
            shpwrite <- write.csv(sh,paste0("Drawings", ".csv"))
        })
        
        # Intake Shape CSV
        observeEvent(input$drawingFile, {
            drawFile <- input$drawingFile
            ext <- file_ext(drawFile$datapath)
            req(drawFile)
            validate(need(ext == "csv", "Please upload a csv file."))
            
            ddf <- read.csv(drawFile$datapath, header = TRUE) # The drawing dataframe
            ind <- which(ddf == "Feature") # Index for drawing df to break up the df to redraw the shapes.
            ind <- as.array(ind)
            
            for (i in 1:nrow(ind)) {
                if(i != nrow(ind)) thisShape <- ddf[ind[i]:ind[i+1]]
                else thisShape <- ddf[ind[i]:ncol(ddf)]
                
                #####
                if(thisShape[3] == "polyline") {
                    tf <- array(startsWith(names(thisShape),"features.geometry.coordinates"))
                    w <- 1
                    pnts <- array()
                    for (i in 1:nrow(tf)) {
                        if(tf[i] == TRUE) {
                            pnts[w] <- thisShape[i]
                            w <- w+1
                        }
                    }
                    n <- 1
                    m <- 1
                    plng <- array()
                    plat <- array()
                    pnts <- as.array(pnts)
                    for (j in 1:nrow(pnts)) {
                        if(j %% 2 == 1) {
                            plng[n] <- pnts[j]
                            n <- n+1
                        }
                        else if(j %% 2 == 0) {
                            plat[m] <- pnts[j]
                            m <- m+1
                        }
                    }
                    as.vector(plng, mode = "any")
                    as.vector(plat, mode = "any")
                    PL <- data.frame(matrix(unlist(plng)))
                    PLsub <- data.frame(matrix(unlist(plat)))
                    PL <- cbind(PL, PLsub)
                    colnames(PL) <- c("lng","lat")
                    PL1 <- reactiveVal(PL)
                    
                    proxy <- leafletProxy("mymap", data = PL1())
                    proxy %>% addPolylines(lng = ~lng, lat = ~lat, group = "draw")
                }
                #####
                else if(thisShape[3] == "polygon") {
                    tf <- array(startsWith(names(thisShape),"features.geometry.coordinates"))
                    w <- 1
                    pnts <- array()
                    for (i in 1:nrow(tf)) {
                        if(tf[i] == TRUE) {
                            pnts[w] <- thisShape[i]
                            w <- w+1
                        }
                    }
                    n <- 1
                    m <- 1
                    plng <- array()
                    plat <- array()
                    pnts <- as.array(pnts)
                    for (j in 1:nrow(pnts)) {
                        if(j %% 2 == 1) {
                            plng[n] <- pnts[j]
                            n <- n+1
                        }
                        else if(j %% 2 == 0) {
                            plat[m] <- pnts[j]
                            m <- m+1
                        }
                    }
                    as.vector(plng, mode = "any")
                    as.vector(plat, mode = "any")
                    PG <- data.frame(matrix(unlist(plng)))
                    PGsub <- data.frame(matrix(unlist(plat)))
                    PG <- cbind(PG, PGsub)
                    colnames(PG) <- c("lng","lat")
                    PG1 <- reactiveVal(PG)
                    
                    proxy <- leafletProxy("mymap", data = PG1())
                    proxy %>% addPolygons(lng = ~lng, lat = ~lat, group = "draw")
                }
                #####
                else if(thisShape[3] == "rectangle"){
                    rlng1 <- as.numeric(thisShape[5])
                    rlat1 <- as.numeric(thisShape[6])
                    rlng2 <- as.numeric(thisShape[9])
                    rlat2 <- as.numeric(thisShape[10])
                    
                    proxy <- leafletProxy("mymap")
                    proxy %>% addRectangles(lng1 = rlng1, lat1 = rlat1, lng2 = rlng2, lat2 = rlat2,
                                            group = "draw")
                }
                #####
                else if(thisShape[3] == "circle"){
                    crad <- as.numeric(thisShape[4])
                    clng <- as.numeric(thisShape[6])
                    clat <- as.numeric(thisShape[7])
                    
                    proxy <- leafletProxy("mymap")
                    proxy %>% addCircles(lng = clng, lat = clat, radius = crad, group = "draw")
                }
                #####
                else if(thisShape[3] == "marker") {
                    mlng <- as.numeric(thisShape[5])
                    mlat <- as.numeric(thisShape[6])
                    
                    proxy <- leafletProxy("mymap")
                    proxy %>% addMarkers(lng = mlng, lat = mlat, group = "draw")
                }
                #####
                else if(thisShape[3] == "circlemarker") {
                    cmlng <- as.numeric(thisShape[6])
                    cmlat <- as.numeric(thisShape[7])
                    
                    proxy <- leafletProxy("mymap")
                    proxy %>% addCircleMarkers(lng = cmlng, lat = cmlat, group = "draw")
                }
            }
        })
    }
    
    shinyApp(ui = ui, server = server)
    
    

    【讨论】:

      猜你喜欢
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      • 2019-03-07
      • 1970-01-01
      相关资源
      最近更新 更多