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

在R中调用Google Maps API计算多地址对出行时间无结果求助

问题:调用Google Maps Directions API无返回结果,咨询费用与配额问题

我是编程新手,已经尽可能跟着教程写代码,但所有地址对的出行时间计算都返回“无出行时间”,怀疑问题出在Google Maps API端而非代码本身。

我的代码

api_key <- 'IthinkIshouldNdtTellYOU'

desired_arrival_time <- as.POSIXct(paste(next_wednesday, "09:00:00"), tz = "America/New_York")
arrival_epoch_time <- as.numeric(desired_arrival_time)

get_travel_time <- function(origin, destination, api_key, arrival_time) {
  base_url <- "https://maps.googleapis.com/maps/api/directions/json?"
  query <- paste0("origin=", URLencode(origin),
              "&destination=", URLencode(destination),
              "&mode=transit",
              "&arrival_time=", arrival_time,
              "&key=", api_key)
  response <- GET(paste0(base_url, query))

  if (response$status_code == 200) {
    data <- fromJSON(rawToChar(response$content))
    if (length(data$routes) > 0) {
      travel_time <- data$routes[[1]]$legs[[1]]$duration$text
      return(travel_time)
    } else {
      return(NA)
    }
  } else {
    stop("API request failed with status code: ", response$status_code)
  }
}

address_pairs$travel_time <- NA

for (i in 1:nrow(address_pairs)) {
  travel_time_result <- try(
    get_travel_time(
      origin = address_pairs$OriginAdd[i],
      destination = address_pairs$DestinAdd[i],
      api_key = api_key,
      arrival_time = arrival_epoch_time
    ),
    silent = TRUE  # 设为TRUE避免直接打印错误信息
  )

  if (class(travel_time_result) == "try-error") {
    address_pairs$travel_time[i] <- NA
    print(paste("Error on row", i, ":", travel_time_result))
  } else {
    # 无错误时,检查函数是否返回有效数据
    if (!is.na(travel_time_result) && length(travel_time_result) > 0) {
      address_pairs$travel_time[i] <- travel_time_result
    } else {
      # 函数返回NA或空值时赋值NA
      address_pairs$travel_time[i] <- NA
      print(paste("No travel time returned for row", i))
    }
  }

  Sys.sleep(0.2) # 注意API调用频率限制
}

运行结果

No travel time returned for row 1208
No travel time returned for row 1209
No travel time returned for row 1210

地址样本

OriginAdd                           DestinAdd
365 Fifth Ave, Manhattan, New York  120 Schermerhorn St, Brooklyn, NY 11201
3280 46th Avenue, Queens, Corona, NY    265 E 161 St, Bronx, NY 10451
106-05 37 Avenue, Queens, New York .    125-01 Queens Blvd, Queens, NY 11415
3280 46th Street, Queens, NY    265 E 161 St, Bronx, NY 10451
475 48th Ave, Queens, New York 11109    100 Centre St, New York, NY 10013

疑问点

  • 能看到API密钥被调用,但始终无结果;地址均为纽约市地址,Google Maps在该区域服务正常,RStudio查询耗时较长但无返回
  • 看不懂Google Cloud账户里的内容,想确认该操作是否会产生费用,以及是否已经超出API配额
  • 代码主要借助ChatGPT生成

内容的提问来源于stack exchange,提问作者David J.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:45:01