R中反向地理编码循环的下标超出范围 [英] Subscript out of bounds for reverse geocoding loop in R

查看:53
本文介绍了R中反向地理编码循环的下标超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Google api密钥对数据集进行地理编码.我设法运行了代码,并得到了一个较小的10个样本的预期结果,但它给出了一个错误

I am attempting to reverse geocode a data-set using the google api key. I managed to run the code and get the desired results for a small sample of 10, but it gives an error

Error in rgc$results[[1]] : subscript out of bounds

我通过使用以下代码设法集成了api密钥:

I managed to integrate the api key by using the following code:

` revgx <- mapply(function(latlng, api_key){


url= paste("https://maps.googleapis.com/maps/api/geocode/json?","latlng=",latlng,"&key=",sep="")

rgc <- fromJSON(paste(readLines(url), collapse = ''))

rgc <- rgc$results[[1]]


with(rgc,{rgcdf <<- data.frame(
address = formatted_address
)})
for(k in seq_along(rgc$address_components)){
rgcdf <- cbind(rgcdf, rgc$address_components[[k]]$long_name)
}
names(rgcdf) <- c('address', sapply(rgc$address_components, function(l)     l$types[1]))

# return 'more' output
rgcdf
},
y1$latlng)`

我也尝试将其与xml合并使用,但无济于事.请建议是否需要对代码进行任何更改.

I tried using the same with incorporating xml too, but to no avail. Please suggest if any changes are required to be made to the code.

推荐答案

我测试了您的代码,并且对我有用.但是您并没有在测试状态.如果latlng不正确,它将返回零结果"作为状态(并且不存在rgc $ results).这是我测试过的代码.

I tested your code and it's working for me. But you aren't testing for status. If latlng is incorrect, it return "ZERO RESULTS" as status (and no rgc$results exist). Here's the code that I tested.

rev <- function(latlng, api_key) {

url= url(paste("https://maps.googleapis.com/maps/api/geocode/json?","latlng=",latlng,"&key=",sep=""))
rgc <- fromJSON(paste(readLines(url), collapse = ''))
close(url)

if (rgc["status"] == "OK") {
    rgc <- rgc$results[[1]]
    with(rgc, {
        rgcdf <<- data.frame(address = formatted_address)
    })
    for (k in seq_along(rgc$address_components)) {
        rgcdf <- cbind(rgcdf, rgc$address_components[[k]]$long_name)
    }
    names(rgcdf) <- c("address", sapply(rgc$address_components, function(l) l$types[1]))
    rgcdf["valid_latlong"] <- TRUE
    rgcdf
} else {
    rgcdf <- c(valid_latlong=FALSE)
}
}

我用以下方法对此进行了测试:

I tested this with:

rev("12.9756300,77.6066230")

您是否以这种格式传递latlng?或c(9756300,77.6066230).那你需要做

Are you passing latlng in this format? Or c(9756300,77.6066230) . Then you need to do

latlng <-  gsub(' ','%20', paste(latlng, collapse=","))

您还没有在共享的代码段中集成api密钥.传递api_key来查询参数.

Also you haven't integrated api key in the code snippet that you shared. Pass api_key to query param.

这篇关于R中反向地理编码循环的下标超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆