如何在gmapsdistance R包中传入多个出发日期与时间参数?
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_vectoris formatted asYYYY-MM-DDandtime_vectorasHH: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

