我有一个小的Shiny应用程序 - 代码如下。这个想法是用户能够编辑,添加和删除点和多边形。因为最终产品将是两个shapefile(一个点,一个多边形),我需要将数据分开(并且很可能它们将具有不同的属性,因此将它们组合到一个数据集中不是选项)。
我的解决方案是每次都会生成mapview,具体取决于用户选择编辑的内容。我很高兴这很好用 - 但每次发生这种情况时,地图视图的范围都会重置为数据范围。我想找到一些方法来在更新之前捕获当前范围,以便我可以在setView
中使用它来保持相同的范围。有没有办法做到这一点? Mapview似乎没有这个功能,我不确定我怎么可能与Leaflet谈谈从这一点实现它。
任何帮助表示感谢。
应用:
library(shiny)
library(leaflet)
library(RColorBrewer)
library(rgdal)
library(leaflet.extras)
library(mapedit)
library(mapview)
library(sp)
workSpace <- "C:/temp"
myPoints <<- readOGR(workSpace,"Points")
myPolys <<- readOGR(workSpace,"Polys")
## Remove a few unneccesary attributes (for this exercise, anyway):
myPolys$Shape_Leng <- NULL
myPolys$Shape_Area <- NULL
myPoints$Shape_Leng <- NULL
myPoints$Shape_Area <- NULL
myPolys$OBJECTID <- NULL
myPoints$OBJECTID <- NULL
ui <- bootstrapPage(
tags$style(type= "text/css", "html, body {width:100%;height:100%}"),
editModUI("test-edit", height = "100%"),
absolutePanel(top=10, right=10,width=300,
wellPanel(style = "opacity: 0.80",
fluidRow(
tags$div(title = "Title",
tags$h4("Select Edit Layer")
)
),
fluidRow(
radioButtons(inputId = "layerChoice", label = NULL, choices = list("Polys" = 1, "Points" = 2))
)
)
)
)
server <- function(input, output, session) {
cntr_coords <- c(mean(coordinates(myPolys)[,1]), mean(coordinates(myPolys)[,2]))
myMap <<- (mapview(myPolys) + mapview(myPoints))@map %>% setView(cntr_coords[1], cntr_coords[2], zoom = 17)
result <- callModule(editMod, "test-edit", myMap, "myPolys")
observeEvent(input$layerChoice, {
if (input$layerChoice == 1)
{
result <- callModule(editMod, "test-edit", myMap, "myPolys")
}
else
{
result <- callModule(editMod, "test-edit", myMap, "myPoints")
}
})
observe({req(result()$finished)
## Code here to save edits
showModal(modalDialog(title = "Confirm save",
"Do you want to save your edit?",
footer = tagList(
modalButton("Cancel"),
actionButton("ok", "OK")
)))
})
observeEvent(input$ok, {
## Write the data to the existing data
## firstly get the result.
newData <- result()$finished
if (input$layerChoice == 1) {
## Coerce into spatial data frame
newPoly <- as(newData, "Spatial")
## Add required columns and give them a value (this will become a menu)
newPoly$NAME <- "NewName"
newPoly$CODE <- "CodeNEW"
newPoly$Attrib1 <- "New Attrib"
newPoly$Attrib2 <- 8888
## Drop the attributes we don't want
newPoly$X_leaflet_id <- NULL
newPoly$feature_type <- NULL
## Now merge with the existing data
myPolys <<- rbind(myPolys, newPoly)
}
else
{
newPoint <- as(newData, "Spatial")
## Add required columns etc
newPoint$NAME <- "NewPointName"
newPoint$CODE <- "CodePt"
## Drop the attributes we don't want
newPoint$X_leaflet_id <- NULL
newPoint$feature_type <- NULL
## Now merge with the existing data
myPoints <<- rbind(myPoints, newPoint)
}
## Refresh the map
myMap <<- (mapview(myPolys) + mapview(myPoints))@map
## Close the menu
removeModal()
})
}
# Run the application
shinyApp(ui = ui, server = server)
我的数据文件在这里但很容易复制: