不完全确定您的第一个问题,因为我不知道可以使用 mapview() 分配的任何方式。但是,这是使用addPolygons() 的可重现解决方案:
library(dplyr)
library(shiny)
library(leaflet)
library(leaflet.extras)
library(rgdal)
library(sp)
library(tigris)
library(htmltools)
setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) # set your working directory
philly <- tracts(state = 'PA', county = c('Philadelphia'))
ui <- fluidPage(
title = "Test Map",
leafletOutput("mymap", width = 600)
)
server <- function(input, output, session) {
RV <- reactiveValues(Clicks=list()) # used for storing leaflet variables
tract_labels <- sprintf( # labels for mouseover tooltip
"<strong>%s</strong>, <strong>%s</strong>
<br/><b>Land Area:</b> %s",
philly$COUNTYFP,
philly$STATEFP,
philly$ALAND
) %>% lapply(htmltools::HTML)
output$mymap <- renderLeaflet({ # leaflet map
leaflet(data = philly) %>%
setView(-75.16, 39.9523, zoom = 10) %>%
addTiles(urlTemplate = "https://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png",
attribution = NULL) %>%
addPolygons(data = philly,
layerId = philly@data$ALAND,
group = "regions",
fillColor = "#bdd7e7",
weight = 1,
opacity = 1.0,
fillOpacity = 0.5,
smoothFactor = 0.5,
label = tract_labels,
labelOptions = labelOptions(
style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "12px",
direction = "auto"),
highlightOptions = highlightOptions(color = "white",
weight = 2,
bringToFront = TRUE))
})
observeEvent({input$mymap_shape_click}, {
#create object for clicked polygon
click <- input$mymap_shape_click
RV$Clicks <- c(RV$Clicks,click$id)
#define leaflet proxy for second regional level map
proxy <- leafletProxy("mymap")
#subset regions shapefile by the clicked on polygons
selectedReg <- philly[philly@data$ALAND == click$id,]
#map clicked on polygons
proxy %>% addPolygons(data = selectedReg,
fillColor = "red",
fillOpacity = 1,
weight = 1,
color = "black",
stroke = T,
group = "selected",
layerId = selectedReg@data$ALAND)
# remove polygon group that are clicked twice
if(click$group == "selected"){
proxy %>%
clearGroup(group = "selected")
RV$Clicks <- 0 # resets values if polygons are clicked twice
}
mean.land <- mean(as.numeric(RV$Clicks)) # stores the values of polygons that are clicked
print(mean.land)
})
}
shinyApp(ui, server)
基本上地图有两层:基本区域层和另一个区域多边形,突出显示您单击的内容。您可以单击每个多边形以从每个多边形中“检索”一个值(在本例中为土地面积或变量 ALAND)并对其进行计算。这里我选择了三个多边形,并使用了mean.land 变量来显示所有三个的平均土地面积。
reactiveValues RV 对象用于在您单击的任何多边形上存储 layerId 变量的数值。这允许您存储和“检索”它以用于您可能想要进行的其他计算。
[1] 717210 # first click, first value
[1] 571940 # second click, averaged value
[1] 488678.3 # third click, averaged value
您可以通过更改代码中对变量 ALAND 的任何引用来更改提取 layerId 属性。