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

Shiny中Leaflet地图点击标记后切换颜色的实现方法咨询

实现方法

你可以通过leafletProxy动态更新指定标记的图标样式,无需重绘整个地图,具体修改逻辑如下:

  1. 提前定义蓝色(未选中)和红色(选中)两种状态的标记图标
  2. 初始化地图时所有标记默认使用蓝色图标
  3. 在标记点击的监听事件中,根据选中状态动态替换对应ID的标记图标

下面是完整可运行的修改后代码:

library("shiny")
library("sf")
library("leaflet")
library("rgeos")

getData <- function(){
  sf_poly <- "POLYGON ((7.207031 46.97463, 7.182312 46.89868, 7.267456 46.86864, 7.392426 46.85831, 7.529755 46.86864, 7.67807 46.90618, 7.683563 46.97557, 7.592926 47.03082, 7.371826 47.01584, 7.207031 46.97463))"
  sf_poly <- st_as_sf(readWKT(sf_poly))
  points <- st_as_sf(st_sample(sf_poly, 20))
  points$id <- 1:nrow(points)
  coords <- st_coordinates(points)
  df <- data.frame(st_drop_geometry(points), coords)
  return(df)
}

ui <- fluidPage(
  titlePanel("Leaflet Map"),
  sidebarLayout(
    sidebarPanel(
      textInput(inputId="selected_photos", label="Selected images", value = "", placeholder = NULL)
    ),
    mainPanel(
      leafletOutput("mymap")
    )
  )
)

server <- function(input, output, session) {
  points <- getData()
  
  # 定义默认蓝色未选中图标
  default_icon <- awesomeIcons(
    icon = 'map-marker',
    iconColor = '#ffffff',
    library = 'fa',
    markerColor = 'blue'
  )
  
  output$mymap <- renderLeaflet({
    leaflet() %>%
      addProviderTiles("OpenStreetMap", group = "OSM") %>%
      addMarkers(data = points, lng = ~X, lat = ~Y, layerId = ~id, icon = default_icon)
  })
  
  d <- c()
  values <- reactiveValues(df = data.frame(photo_ids=d))
  
  newEntry <- observeEvent(input$mymap_marker_click,{
    clicked_id <- input$mymap_marker_click$id
    selected_photos <- values$df$photo_ids
    
    if( clicked_id %in% selected_photos ){
      selected_photos <- selected_photos[!selected_photos %in% clicked_id]
      new_color <- "blue"
    } else {
      selected_photos <- c(selected_photos, clicked_id)
      new_color <- "red"
    }
    
    values$df <- data.frame(photo_ids=selected_photos)
    updateTextInput(inputId = "selected_photos", session = session, value = paste(unlist(values$df), collapse = ",") )
    
    # 动态更新当前点击标记的颜色
    clicked_point <- points[points$id == clicked_id, ]
    new_icon <- awesomeIcons(
      icon = 'map-marker',
      iconColor = '#ffffff',
      library = 'fa',
      markerColor = new_color
    )
    
    leafletProxy("mymap") %>%
      removeMarker(layerId = clicked_id) %>%
      addMarkers(
        data = clicked_point,
        lng = ~X,
        lat = ~Y,
        layerId = ~id,
        icon = new_icon
      )
  })
}

shinyApp(ui, server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:12:00