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

leaflet调用addPolylines提示经纬度需为数值类型的问题咨询

问题根源

报错核心是2个JSON解析+Leaflet适配的常见问题:

  • 用read_json读取返回的坐标数组后,直接rbind生成的df.routen的X1、X2列是列表类型,不是Leaflet要求的数值向量,哪怕列表内存储的都是数值,也会触发类型校验错误
  • 你当前的代码仅提取了返回结果中第2条自行车路线的坐标,没有批量处理所有路线数据

修正方案

1. 单条路线调试(对应你当前绘制第2条路线的需求)

把列表列转成纯数值向量即可正常运行:

library(leaflet)
library(jsonlite)

api.velo.basel <- "https://data.bs.ch/api/records/1.0/search/?dataset=100032&q=&rows=21"
json.velorouten.basel <-  read_json(api.velo.basel)

# 提取第2条路线坐标,转成矩阵后再转data.frame,确保列是数值类型
coord_matrix <- do.call(rbind, json.velorouten.basel[["records"]][[2]][["fields"]][["geo_shape"]][["coordinates"]])
df.routen <- as.data.frame(coord_matrix)
colnames(df.routen) <- c("lng", "lat")

# 绘制不会再报错
x <- leaflet() %>%
  addTiles() %>%
  addPolylines(data = df.routen,  lng = ~lng, lat = ~lat)
x

2. 绘制所有返回的自行车路线

如果要把21条路线全部渲染,遍历所有records提取坐标批量添加图层即可:

library(leaflet)
library(jsonlite)
library(purrr)

api.velo.basel <- "https://data.bs.ch/api/records/1.0/search/?dataset=100032&q=&rows=21"
json.velorouten.basel <-  read_json(api.velo.basel)

# 初始化底图
x <- leaflet() %>% addTiles()

# 遍历所有路线添加折线
walk(json.velorouten.basel$records, function(rec) {
  coord_mat <- do.call(rbind, rec$fields$geo_shape$coordinates)
  df <- as.data.frame(coord_mat)
  colnames(df) <- c("lng", "lat")
  x <<- x %>% addPolylines(data = df, lng = ~lng, lat = ~lat, color = "red", weight = 2)
})

x

校验方法

你可以执行str(df.routen)查看列类型,修正后lng和lat列会显示为num(数值类型),而非List of xxx,即可被Leaflet正常识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:21:01