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

R语言使用Leaflet时Awesome Markers图标不显示问题求助

问题原因

你遇到的图标不显示问题是两个代码错误导致的:

  • 调用sf::st_as_sf将数据转为空间矢量格式时,你指定了coords = c("lon","lat"),此时原数据中的lon、lat两列会被合并到geometry列中并删除原列,后续addAwesomeMarkers中调用~lon、~lat会找不到坐标参数,标记无法正常渲染。
  • 你用cbind(lon,lat,name,count)拼接数据时,因为name是字符串类型,cbind会自动将所有列统一转为字符型,count列不再是数值,导致getColor中的数值区间判断逻辑完全失效。

修正后的可运行代码

# 加载包(install.packages部分运行过一次就可以注释掉)
library(leaflet)
library(sf)

# 你的原始数据集
start_stations <-
  data.frame(
    station = c("StreeterDr", "MichiganAve", "WellsSt"),
    lat = c(41.89228, 41.90096, 41.91213),
    lng = c(-87.61204,-87.62378,-87.63466),
    n = c(23000, 56780, 34520)
  )

# 直接将原始数据转为sf格式,避免列类型被强制转换
dfs <- st_as_sf(start_stations, coords = c("lng","lat"), crs = 4326)

# 颜色匹配函数,确保count是数值型
getColor <- function(count) {
  sapply(count, function(x) {
    if(x <= 20000) {
      "green"
    } else if(x <= 30000) {
      "orange"
    } else {
      "red"
    } 
  })
}

# 生成图标
icons <- awesomeIcons(
  icon = 'ios-close',
  iconColor = 'black',
  library = 'ion',
  markerColor = getColor(dfs$n)
)

# 绘图,sf对象不需要手动指定lon和lat参数,会自动读取geometry列的坐标
leaflet(dfs) %>% 
  addTiles() %>%
  addAwesomeMarkers(icon=icons, popup = ~station, label=~as.character(n))

运行上述代码即可正常显示对应颜色的标记,同时弹窗显示站点名、悬浮显示站点数量的功能也能正常使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:24:05