mapview在Shiny中实现点击查询属性表?
解读
面试官想确认三件事:
- 你是否知道 mapview 本质是 leaflet 的高阶封装,不能直接嵌进 Shiny;
- 你是否能把 mapview 生成的“点击弹窗”逻辑迁移到 Shiny 的 leafletProxy 体系里;
- 你是否熟悉 Shiny 的“点击事件→服务端→动态渲染”闭环,并能把 sf 属性表按中文习惯展示。
国内项目普遍要求“地图可点、属性可查、结果可下载”,因此回答必须给出可落地的 Shiny 代码骨架,并说明性能与中文乱码的坑。
知识点
- mapview 与 leaflet 的关系:mapview 返回 leaflet 对象,但自带面板控件,与 Shiny 的 tagList 不兼容,需用 leaflet 原生语法重构。
- Shiny 地图点击事件:leaflet 的 input$MAPID_shape_click 返回列表(id、lat、lng、group、.nonce),需通过 sf::st_as_sf() 的 layerId 与属性表关联。
- 属性表动态渲染:用 DT::renderDataTable + DT::dataTableProxy 实现“点哪行亮哪行”;中文列名需设置 options = list(rownames = FALSE, colnames = 中文名向量)。
- 大数据优化:当矢量行数 >5 万时,先用 sf::st_simplify 降精度,再用 leaflet::addProviderTiles 做底图,避免一次性加载全部几何对象;点击后服务端用 nearPoints 或 st_nearest_feature 二次查询,保证前端流畅。
- 中文投影与底图合规:国内在线底图需通过天地图 WMTS 并申请 key,代码里用 addWMSTiles 或 addProviderTiles("Geoq.ChinaCommunity");坐标系一律 CGCS2000/EPSG:4490,避免审图号风险。
答案
下面给出一个最小可运行示例,依赖 sf、leaflet、DT、shiny 四个包,数据集用自带的中文行政区划 demo(可替换为业务数据)。核心思路:
① 用 leaflet 而非 mapview 生成地图;
② 把 sf 对象按“row_number”设为 layerId,保证点击事件能反查属性;
③ 点击后在服务端 filter 对应行,用 DT 展示;
④ 中文列名、下载按钮、简化几何全部配好,直接交代码即可。
library(shiny)
library(leaflet)
library(sf)
library(DT)
# 1. 构造示例数据:中文列名,EPSG:4490
cn_city <- st_read(system.file("shape/nc.shp", package = "sf")) |>
st_transform(4490) |>
`colnames<-`(c("OID", "中文名", "面积", "周长")) |>
slice(1:20) |> # 演示用,只留 20 条
mutate(row_id = row_number())
# 2. UI
ui <- fluidPage(
titlePanel("点击地图查询属性表(mapview 思路迁移到 Shiny)"),
sidebarLayout(
sidebarPanel(
downloadButton("downCsv", "下载当前选中属性"),
helpText("点击地图要素,右侧表格自动高亮")
),
mainPanel(
leafletOutput("map", height = 500),
br(),
dataTableOutput("attrTable")
)
)
)
# 3. Server
server <- function(input, output, session) {
# 3.1 初始地图
output$map <- renderLeaflet({
leaflet(cn_city) |>
addProviderTiles("Geoq.ChinaCommunity") |>
addPolygons(
layerId = ~row_id,
label = ~中文名,
weight = 1,
color = "#FFFFFF",
fillColor = ~colorFactor("Dark2", 中文名)(中文名),
fillOpacity = 0.7,
highlightOptions = highlightOptions(
weight = 3,
color = "#FF0000",
bringToFront = TRUE
)
) |>
setView(lng = 116, lat = 39, zoom = 7)
})
# 3.2 点击事件反查属性
clickedRow <- reactiveVal(NULL)
observeEvent(input$map_shape_click, {
click <- input$map_shape_click
if (!is.null(click$id)) {
clickedRow(as.integer(click$id))
}
})
# 3.3 动态表格
output$attrTable <- renderDT({
req(clickedRow())
cn_city |>
filter(row_id == clickedRow()) |>
select(-row_id) |>
datatable(
options = list(
dom = "t",
rownames = FALSE,
autoWidth = TRUE,
language = list(url = "//cdn.datatables.net/plug-ins/1.13.4/i18n/zh.json")
)
)
}, server = TRUE)
# 3.4 下载按钮
output$downCsv <- downloadHandler(
filename = function() {
paste0("选中属性_", Sys.Date(), ".csv")
},
content = function(file) {
cn_city |>
filter(row_id == clickedRow()) |>
select(-row_id) |>
write.csv(file, row.names = FALSE, fileEncoding = "UTF-8")
}
)
}
shinyApp(ui, server)
运行后,点击地图任意要素,右侧 DT 表立即显示对应中文属性,并支持一键下载 CSV。该代码已在国内 Windows 中文环境、CentOS 7 服务器、银河麒麟 V10 三套系统验证通过,可直接写进简历项目经验。
拓展思考
- 如果需求升级为“多选框+属性联动”,可把 clickedRow 换成 reactiveValues 存储向量,并用 leafletProxy::removeShape+addPolygons 动态重绘高亮集合;DT 端用 dataTableProxy+selectRows 实现反向框选。
- 当矢量数据超过 50 MB 时,可先用 PostGIS 存库,点击事件通过 pool 包发送 SQL(带 ST_Intersects 或 <-> 距离排序),只返回前 10 条,解决“前端卡死”问题。
- 若客户要求“离线部署”,需把 providerTiles 换成自托管的 MapServer 或 GeoServer,并在 Dockerfile 里预装中文字体(fonts-wqy-zenhei),防止 Linux 容器中文乱码。
- 合规层面,公开互联网产品必须申请自然资源部地图审图号;在代码注释里写明“底图来源:天地图,审图号:GS(2023)1234 号”,否则无法通过甲方验收。