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

如何修复ggmap中使用mapdist调用API时出现的错误?

问题:计算城镇到学校的距离时遇到匹配错误

我有一个包含学区及所使用的外区学校的data frame,共4800行,每行包含城镇、学校及坐标信息。想要在该data frame中新增一列,存储每行中城镇到对应学校的距离,但反复遇到相同错误。

尝试的代码

for (row in 1:nrow(special_ed)){
    z <- mapdist(from = special_ed$Sending.District, to = special_ed$Coords, mode = "driving", source = 'google', api_key = api_secret)
    special_ed <- special_ed %>% mutate(dist = z)
}

报错信息

! Matching was not perfect, returning all.
Error in map():
ℹ In index: 1.
Caused by error in `*tmp*`[[c(1, 1)]]:
! no such index at level 1

问题分析与解决

这个错误不是Google Maps API请求超限导致的,核心问题出在代码逻辑上:

  1. 循环逻辑错误:你的循环每次都传入整个Sending.District和Coords列,而非当前行的单个地址/坐标,导致mapdist一次性处理4800条请求,触发地址匹配混乱。
  2. 列赋值错误:mapdist返回的是完整数据框,你直接用mutate(dist = z)把整个数据框赋值给单列,数据结构不匹配,这才是报错的直接原因。

修正方案

方案1:正确的逐行处理(带防超限延迟)

# 先初始化距离列
special_ed$dist <- NA

for (row in 1:nrow(special_ed)) {
  # 提取当前行的起点和终点
  from_addr <- special_ed$Sending.District[row]
  to_coord <- special_ed$Coords[row]
  
  # 仅处理当前行的请求
  z <- mapdist(from = from_addr, to = to_coord, mode = "driving", source = 'google', api_key = api_secret)
  
  # 提取距离值赋值给对应行
  special_ed$dist[row] <- z$distance
  
  # 加1秒延迟,避免触发API频率限制
  Sys.sleep(1)
}

方案2:高效批量处理(推荐)

如果mapdist支持批量传入向量,可直接一次性处理(需注意API配额):

# 批量计算所有距离
z <- mapdist(from = special_ed$Sending.District, to = special_ed$Coords, mode = "driving", source = 'google', api_key = api_secret)

# 将距离结果关联到原数据框
special_ed$dist <- z$distance

若批量请求触发API限制,可分批次处理(比如每500条为一组,每组间加延迟)。

补充:API超限的错误特征

如果是API请求超限,Google会返回明确的提示,比如Quota exceeded或Rate limit exceeded,和当前的索引匹配错误完全不同。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:01:25