代码之家  ›  专栏  ›  技术社区  ›  marine8115

R中反向地理编码循环的下标越界

  •  1
  • marine8115  · 技术社区  · 9 年前

    我正在尝试使用googleapi键对数据集进行反向地理编码。我成功地运行了代码,得到了一个小样本10的期望结果,但它给出了一个错误

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

    我使用以下代码成功地集成了api密钥:

    ` 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,但没有成功。请建议是否需要对代码进行任何更改。

    1 回复  |  直到 9 年前
        1
  •  2
  •   khrm    9 年前

    我测试了你的代码,它对我来说很有效。但你不是在测试状态。如果latlng不正确,则返回“ZERO RESULTS”作为状态(不存在rgc$RESULTS)。这是我测试的代码。

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

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

    rev("12.9756300,77.6066230")
    

    你是以这种形式通过考试吗?或者c(9756300,77.6066230)

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

    此外,您还没有在共享的代码段中集成api键。将api_key传递给查询参数。

    推荐文章