从 R 中的 Google 地理编码 API 创建位置名称列表

Creating a list of location names from Google geocoding API in R

我是 R 的新手,我在使用 Google 地理编码 API 编写的用于从邮政编码列表创建位置名称列表的 for 循环时遇到问题。这是一个基于我目前已有的示例:

library(RCurl)
library(rjson)

zips <- c("10001", "10002", "10003","10004","10005","10006")

test <- NULL  
temp <- NULL  
for (i in 1:length(zips)) {
    temp[i] = fromJSON(getURL(paste('http://maps.googleapis.com/maps/api/geocode/json?address=', zips, sep="")))
    test[i] <- temp$results[[1]]$formatted_address
    Sys.sleep (.3) #Google limits your API calls to 5 per second.
}

非常感谢您的帮助!

在您的代码中,您缺少一个 [i] 子集来读取 zip。 这应该有效:

library(RCurl)
library(rjson)

zips <- c("10001", "10002", "10003","10004","10005","10006")

tmp <- NULL
test <- vector("character", length(zips))
for (i in 1:length(zips)) {
    tmp <- fromJSON(getURL(paste('http://maps.googleapis.com/maps/api/geocode/json?address=', zips[i], sep="")))
    test[i] <- tmp$results[[1]]$formatted_address
    Sys.sleep (.3) #Google limits your API calls to 5 per second.
}

print(test)  

## [1] "New York, NY 10001, USA" "New York, NY 10002, USA" "New York, NY 10003, USA"
## [4] "New York, NY 10004, USA" "New York, NY 10005, USA" "New York, NY 10006, USA"