Subscript out of bounds for reverse geocoding loop in R

馋奶兔 提交于 2021-02-08 08:12:52

问题


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

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)`

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.


回答1:


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")

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

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

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



来源:https://stackoverflow.com/questions/37244301/subscript-out-of-bounds-for-reverse-geocoding-loop-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!