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

在R中调用Google Distance Matrix API遭遇查询限制问题

生成多地点间的距离矩阵(基于Google Maps API)

嘿,你选的工具组合完全没问题!用googleway调用Google Maps的距离API,再结合plyr处理数据,刚好能搞定36个地点的距离矩阵需求。我把你给出的演示代码补全并梳理清楚,方便你直接适配到36个地点的场景:

# 加载所需包
library(googleway)
library(plyr)
library(tidyr) # 额外加载用于整理矩阵格式

# 设置Google Maps API密钥(建议用环境变量存储,不要硬编码在公开代码里)
key <- Sys.getenv("GOOGLE_MAPS_API_KEY") # 替换成你的有效密钥,也可直接赋值但注意保密

# 示例地点列表(替换成你的36个地点即可)
districts <- c(
  "Attock, Pakistan", 
  "Bahawalnagar, Pakistan", 
  "Bahawalpur, Pakistan", 
  "Bhakkar, Pakistan"
)

# 生成所有地点的两两组合(包含地点到自身的情况)
location_pairs <- expand.grid(origin = districts, destination = districts, stringsAsFactors = FALSE)

# 调用Google Distance API批量获取距离数据
distance_data <- plyr::mdply(
  .data = location_pairs,
  .fun = function(origin, destination) {
    res <- google_distance(
      origin = origin,
      destination = destination,
      key = key,
      mode = "driving" # 可按需替换为"walking"、"bicycling"等出行模式
    )
    # 提取距离数值与格式化文本
    data.frame(
      origin = origin,
      destination = destination,
      distance_m = res$rows$elements[[1]]$distance$value,
      distance_text = res$rows$elements[[1]]$distance$text,
      stringsAsFactors = FALSE
    )
  }
)

# 将长格式数据转换为标准的36×36距离矩阵(以米为单位)
distance_matrix <- distance_data %>%
  select(origin, destination, distance_m) %>%
  pivot_wider(names_from = destination, values_from = distance_m) %>%
  column_to_rownames(var = "origin")

# 查看最终矩阵结果
print(distance_matrix)

关键细节提醒:

  • 成对组合生成:expand.grid会自动生成所有地点的两两配对,确保不会遗漏任何一组地点间的距离计算
  • API安全与配额:
    • 千万别把API密钥直接写在公开代码里,用Sys.getenv读取环境变量是更安全的做法
    • 36个地点会产生36×36=1296次API请求,要提前确认你的Google Maps API配额是否足够,避免触发调用限制
  • 矩阵格式调整:用tidyr::pivot_wider可以快速把长格式的距离数据转换成便于分析的矩阵格式
  • 距离单位:默认返回米,如需公里或英里,可在google_distance中设置units = "metric"或units = "imperial",也可自行做单位转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:10:44