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

如何在mapdeck中使用set_token?运行代码后key为空且无地图显示

解决mapdeck中set_token返回NULL导致地图无法显示的问题

问题根源

你遇到的key变量为NULL的情况,其实是set_token()函数的设计特性导致的:

  • set_token()的作用是将你的Mapbox token设置为全局环境变量,方便后续所有mapdeck调用自动读取,它本身不会返回你传入的token字符串,所以当你执行key <- set_token("your_token")时,key自然会被赋值为NULL。
  • 之后你在mapdeck(token = key)中传入了NULL,相当于没有提供有效的token,这就是地图能运行但无法显示的核心原因。

两种正确的解决方案

方案1:使用全局token设置(推荐)

先调用set_token()设置全局token,之后调用mapdeck()时无需再传token参数:

library(mapdeck)
library(leaflet)

# 仅设置全局token,不需要赋值给变量
set_token("pk.eyJ1IjoicmFxdWVsc2FyYWl2YTE5ODgiLCJhIjoiY2p4MzM2eHh5MG95aTN5cDQxdjVocDlxMCJ9.Wskus8QqYwjAufGpW71OVg")

df <- readRDS("df.rds")
df$Station_Long = as.numeric(as.character(df$lon_Pay))
df$Station_Lat = as.numeric(as.character(df$lat_Pay))
df$id = as.factor(as.numeric(as.factor(df$ID)))

# mapdeck会自动读取全局设置的token
mapdeck(style = mapdeck_style('dark'), location = c(104, 1), zoom = 8, pitch = 45) %>% 
  add_arc(data = df, origin = c("centroid_lon", "centroid_lat"), 
          destination = c("lon_Pay", "lat_Pay"), layer_id = 'arclayer', 
          stroke_width = 3, stroke_from = "#ccffff", stroke_to = "#ccffff")

方案2:直接在mapdeck中传入token

如果你不想设置全局变量,可以直接把token字符串传入mapdeck()的token参数:

library(mapdeck)
library(leaflet)

df <- readRDS("df.rds")
df$Station_Long = as.numeric(as.character(df$lon_Pay))
df$Station_Lat = as.numeric(as.character(df$lat_Pay))
df$id = as.factor(as.numeric(as.factor(df$ID)))

# 直接传入token字符串
mapdeck(token = "pk.eyJ1IjoicmFxdWVsc2FyYWl2YTE5ODgiLCJhIjoiY2p4MzM2eHh5MG95aTN5cDQxdjVocDlxMCJ9.Wskus8QqYwjAufGpW71OVg", 
        style = mapdeck_style('dark'), location = c(104, 1), zoom = 8, pitch = 45) %>% 
  add_arc(data = df, origin = c("centroid_lon", "centroid_lat"), 
          destination = c("lon_Pay", "lat_Pay"), layer_id = 'arclayer', 
          stroke_width = 3, stroke_from = "#ccffff", stroke_to = "#ccffff")

额外检查项

  • 确保你的Mapbox token是有效的:可以登录Mapbox账号,在"Access Tokens"页面确认token的状态,以及是否具备地图加载的权限。
  • 确认你的数据转换没有问题:比如centroid_lon、centroid_lat、lon_Pay、lat_Pay这些字段都是有效的数值类型,没有NA或非数值值影响图层渲染。

内容的提问来源于stack exchange,提问作者R. Saraiva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:18:43