You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shiny的tmap交互地图中显示点的全部属性

解决Shiny+tmap点击点位显示自定义属性的问题

核心方案

在tmap的tm_dots函数中,通过popup.vars参数指定需要展示的属性,或使用popup参数自定义弹窗内容,即可实现点击点位时显示状态、经纬度等目标信息。

修正后的完整代码

先修正原代码中的数据转换错误,再添加弹窗配置:

library(dplyr)
library(shiny)
library(tmap)
library(sf)

# 创建数据框
dat <- data.frame(
  lat = c(48.7323,48.7308,48.7301,48.7276,48.7246,48.7323,48.7211),
  long = c(-122.4928,-122.4940,-122.4942,-122.4939,-122.4958,-122.4975,-122.4946),
  species = c("Apple", "Apple", "Pear", "Plum", "Fig", "Plum", "Pear"),
  status = c("Confirmed", "Unconfirmed", "Confirmed", "Confirmed", "Confirmed", "Unconfirmed", "Confirmed")
)

# UI组件
ui <- fluidPage(
  mainPanel(
    tmapOutput(outputId = "tmapMap"),
  )
)

# Server组件
server <- function(input, output, session) {
  output$tmapMap <- renderTmap({
    # 转换为空间点数据框(修正原代码中dat2plot未定义的错误)
    dat2plot <- st_as_sf(dat, coords = c("long","lat"), crs = st_crs("EPSG:4326"))
    
    # 提取经纬度到属性列(方便弹窗直接调用)
    dat2plot <- dat2plot %>%
      mutate(
        latitude = st_coordinates(.)[,2],
        longitude = st_coordinates(.)[,1]
      )
    
    # 绘制带自定义弹窗的地图
    map1 <- tm_shape(dat2plot) +
      tm_dots(
        col = "species", 
        alpha = 0.8, 
        size = 0.1,
        # 指定弹窗显示的变量,可自定义显示标题
        popup.vars = c(
          "树种" = "species",
          "状态" = "status",
          "纬度" = "latitude",
          "经度" = "longitude"
        )
      ) +
      tm_legend(show = TRUE) +
      tm_view(set.zoom.limits = c(14,16))
    
    map1
  })
}

shinyApp(ui = ui, server = server)

关键说明

  1. 修正数据转换错误:原代码中dat2plot <- st_as_sf(dat2plot, ...)属于无效调用,需从原始dat数据框转换生成空间对象。
  2. 提取经纬度属性:sf对象的坐标默认不在属性列中,通过st_coordinates提取并添加为新列,才能在弹窗中展示经纬度信息。
  3. 自定义弹窗样式:
    • 若需要更灵活的HTML格式弹窗,可替换popup.vars为popup参数,示例如下:
      popup = paste0(
        "<strong>树种:</strong> ", dat2plot$species, "<br>",
        "<strong>状态:</strong> ", dat2plot$status, "<br>",
        "<strong>坐标:</strong> ", round(dat2plot$latitude,4), ", ", round(dat2plot$longitude,4)
      )
      

内容的提问来源于stack exchange,提问作者Finn Tobias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 19:57:31