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

如何在gmapsdistance R包中传入多个出发日期与时间参数?

Fixing the XML Error When Using dep_date/dep_time Vectors in gmapsdistance

Hey there! You’re spot-on with your hunch — the dep_date and dep_time parameters in gmapsdistance don’t support vector inputs, which is exactly why you’re hitting that XML format error. When you pass vectors for these arguments, the package generates a malformed request that Google’s Distance Matrix API can’t parse, leading to the "XML declaration allowed only at the start..." message you’re seeing.

Here’s how to fix this:

1. Loop Through Each Date/Time Pair

Since vector inputs aren’t supported, we’ll process each origin-destination-date-time combination one at a time using a loop, then combine the results. Here’s a working example:

# Make sure all your vectors are the same length first
stopifnot(length(origin_vector) == length(destination_vector),
          length(date_vector) == length(time_vector))

# Use lapply to iterate over each index
result_list <- lapply(seq_along(origin_vector), function(i) {
  gmapsdistance(
    origin = origin_vector[i],
    destination = destination_vector[i],
    combinations = "pairwise",
    mode = "driving",
    shape = "long",
    dep_date = date_vector[i],
    dep_time = time_vector[i]
  )
})

# Combine the results into a single data frame (adjust based on your output structure)
final_result <- do.call(rbind, lapply(result_list, function(x) x$Distance))

2. Verify Single Request First (Debug Step)

To confirm this is the issue, test a single request with non-vector inputs — if this works, you’ll know vector inputs were the problem:

# Test with the first element of each vector
test_request <- gmapsdistance(
  origin = origin_vector[1],
  destination = destination_vector[1],
  combinations = "pairwise",
  mode = "driving",
  shape = "long",
  dep_date = date_vector[1],
  dep_time = time_vector[1]
)

# Check if test_request returns valid data
str(test_request)

Quick Notes

  • Double-check your date_vector is formatted as YYYY-MM-DD and time_vector as HH:MM:SS — Google’s API requires these exact formats, and wrong formatting can also trigger XML errors.
  • Keep an eye on your Google API quota! Looping through requests means you’ll make one API call per combination, so make sure you don’t exceed your allowed limits.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:37:29