Я получил ключ API, воспроизведенный вашу проблему, а затем прошел через исходный код линии базовую функцию в построчно.
Ошибка вызвано следующими причинами:
data$Time[i] = as(rowXML[[dur]][1L]$value[1L]$text,
"numeric")
, так как объект dur
содержит только следующее:
> dur
[1] "duration" "duration_in_traffic"
rowXML[[dur]]
Таким образом, бросает ошибку. Я не уверен, где указать пальцем, но очень часто изменения API быстрее, чем пакеты, построенные вокруг них.
Тем не менее, вы все равно можете использовать исходный код, чтобы получить свой результат, как и я. Это займет несколько строк кода, чтобы очистить результаты себя:
xmlChildren(results$row[[1L]])
$status
<status>OK</status>
$duration
<duration>
<value>20185</value>
<text>5 hours 36 mins</text>
</duration>
$distance
<distance>
<value>459271</value>
<text>459 km</text>
</distance>
$duration_in_traffic
<duration_in_traffic>
<value>20957</value>
<text>5 hours 49 mins</text>
</duration_in_traffic>
attr(,"class")
[1] "XMLInternalNodeList" "XMLNodeList"
на ваш запрос в комментарии, вот немного больше о том, что я сделал, чтобы получить это.
Сначала возьмите аргументы из вызова этой функции и создайте из них объекты (т. Е. Просто запустите каждый аргумент как отдельную команду для создания объектов). Затем загрузите библиотеки XML
и Rcurl
. Кроме того, введите ключ API в объект с именем key
.
После этого вы просто берете исходный код функции и запускаете ее по строкам, пропуская часть, где определен вызов функции. По пути есть небольшое количество неиспользуемых аргументов, которые вы можете просто создать и установить на ""
.
# function (origin, destination, combinations = "all", mode, key = #get.api.key(),
# shape = "wide", avoid = "", departure = "now", dep_date = "",
# dep_time = "", traffic_model = "best_guess", arrival = "",
# arr_date = "", arr_time = "") # don't run this
if (!(mode %in% c("driving", "walking", "bicycling", "transit"))) {
stop("Mode of transportation not recognized. Mode should be one of ",
"'bicycling', 'transit', 'driving', 'walking' ")
if (!(combinations %in% c("all", "pairwise"))) {
stop("Combinations between origin and destination not recognized. Combinations should be one of ",
"'all', 'pairwise' ")
}
if (!(avoid %in% c("", "tolls", "highways", "ferries", "indoor"))) {
stop("Avoid parameters not recognized. Avoid should be one of ",
"'tolls', 'highways', 'ferries', 'indoor' ")
}
if (!(traffic_model %in% c("best_guess", "pessimistic", "optimistic"))) {
stop("Traffic model not recognized. Traffic model should be one of ",
"'best_guess', 'pessimistic', 'optimistic'")
}
seconds = "now"
seconds_arrival = ""
UTCtime = strptime("1970-01-01 00:00:00", "%Y-%m-%d %H:%M:%OS",
tz = "GMT")
min_secs = round(as.numeric(difftime(as.POSIXlt(Sys.time(),
"GMT"), UTCtime, units = "secs")))
if (dep_date != "" && dep_time != "") {
depart = strptime(paste(dep_date, dep_time), "%Y-%m-%d %H:%M:%OS",
tz = "GMT")
seconds = round(as.numeric(difftime(depart, UTCtime,
units = "secs")))
}
if (departure != "now") {
seconds = departure
}
if (departure != "now" && departure < min_secs) {
stop("The departure time has to be some time in the future!")
}
if (dep_date != "" && dep_time == "") {
stop("You should also specify a departure time in the format HH:MM:SS UTC")
}
if (dep_date == "" && dep_time != "") {
stop("You should also specify a departure date in the format YYYY-MM-DD UTC")
}
if (dep_date != "" && dep_time != "" && seconds < min_secs) {
stop("The departure time has to be some time in the future!")
}
if (arr_date != "" && arr_time != "") {
arriv = strptime(paste(arr_date, arr_time), "%Y-%m-%d %H:%M:%OS",
tz = "GMT")
seconds_arrival = round(as.numeric(difftime(arriv, UTCtime,
units = "secs")))
}
if (arrival != "") {
seconds_arrival = arrival
}
if (arrival != "" && arrival < min_secs) {
stop("The arrival time has to be some time in the future!")
}
if (arr_date != "" && arr_time == "") {
stop("You should also specify an arrival time in the format HH:MM:SS UTC")
}
if (arr_date == "" && arr_time != "") {
stop("You should also specify an arrival date in the format YYYY-MM-DD UTC")
}
if (arr_date != "" && arr_time != "" && seconds_arrival <
min_secs) {
stop("The arrival time has to be some time in the future!")
}
if ((dep_date != "" || dep_time != "" || departure != "now") &&
(arr_date != "" || arr_time != "" || arrival != "")) {
stop("Cannot input departure and arrival times. Only one can be used at a time. ")
}
if (combinations == "pairwise" && length(origin) != length(destination)) {
stop("Size of origin and destination vectors must be the same when using the option: combinations == 'pairwise'")
}
if (combinations == "all") {
data = expand.grid(or = origin, de = destination)
}
else if (combinations == "pairwise") {
data = data.frame(or = origin, de = destination)
}
n = dim(data)
n = n[1]
data$Time = NA
data$Distance = NA
data$status = "OK"
avoidmsg = ""
if (avoid != "") {
avoidmsg = paste0("&avoid=", avoid)
}
for (i in 1:1:n) {
url = paste0("maps.googleapis.com/maps/api/distancematrix/xml?origins=",
data$or[i], "&destinations=", data$de[i], "&mode=",
mode, "&sensor=", "false", "&units=metric", "&departure_time=",
seconds, "&traffic_model=", traffic_model, avoidmsg)
if (!is.null(key)) {
key = gsub(" ", "", key)
url = paste0("https://", url, "&key=", key)
}
else {
url = paste0("http://", url)
}
webpageXML = xmlParse(getURL(url))
results = xmlChildren(xmlRoot(webpageXML))
request.status = as(unlist(results$status[[1]]), "character")
if (!is.null(results$error_message)) {
stop(paste(c("Google API returned an error: ", xmlValue(results$error_message)),
sep = ""))
}
if (request.status == "REQUEST_DENIED") {
set.api.key(NULL)
data$status[i] = "REQUEST_DENIED"
}
rowXML = xmlChildren(results$row[[1L]])
Status = as(rowXML$status[1]$text, "character")
if (Status == "ZERO_RESULTS") {
data$status[i] = "ROUTE_NOT_FOUND"
}
if (Status == "NOT_FOUND") {
data$status[i] = "PLACE_NOT_FOUND"
}
if (Status == "OVER_QUERY_LIMIT") {
stop("You have exceeded your allocation of API requests for today.")
}
if (data$status[i] == "OK") {
data$Distance[i] = as(rowXML$distance[1]$value[1]$text,
"numeric")
dur = grep("duration", names(rowXML), value = TRUE)
data$Time[i] = as(rowXML[[dur]][1L]$value[1L]$text,
"numeric")
}
}
datadist = data[c("or", "de", "Distance")]
datatime = data[c("or", "de", "Time")]
datastat = data[c("or", "de", "status")]
if (n > 1) {
if (shape == "wide" && combinations == "all") {
Distance = reshape(datadist, timevar = "de", idvar = c("or"),
direction = "wide")
Time = reshape(datatime, timevar = "de", idvar = c("or"),
direction = "wide")
Stat = reshape(datastat, timevar = "de", idvar = c("or"),
direction = "wide")
}
else {
Distance = datadist
Time = datatime
Stat = datastat
}
}
else {
Distance = data$Distance[i]
Time = data$Time[i]
Stat = data$status[i]
}
output = list(Time = Time, Distance = Distance, Status = Stat)
Проверка в консоли API Google, находится ли превышена квота на день – SymbolixAU
Ошибки будет наступающей из [этой линии] (https://github.com/rodazuero/gmapsdistance/blob/831541fc8cd11e289f17daf4f23e332b3356f252/ R/gmapsdistance.R # L258), который мне подсказывает, что вызов API не удался и поэтому не было значения 'duration' – SymbolixAU
. Вы также можете проверить свой код на моем [' googleway'] (https: //cran.r-project .org/web/packages/googleway/index.html), который также вызывает API Карт Google. Если он не работает в обоих пакетах, это говорит о том, что проблема не в коде R – SymbolixAU