R 中的反向地理编码循环

Loop for Reverse Geocoding in R

我正在尝试对大型数据集(大约 100k)进行反向地理编码。我使用了 ggmap 包中的 revgeocode 函数。我得到了 1 个条目的结果

48 Grand View Terrace, San Francisco, 
CA 94114, USA            
48 Grand View Terrace Eureka Valley San Francisco        
San Francisco County                  California United States
postal_code postal_code_suffix

,但我需要自动化该过程并将其用于整个数据集。

我试过了

r <- lapply(revgeocode(location = (c(z$lon),c(z$lat)),
             output = "more",
            messaging = FALSE, sensor = FALSE, override_limit = FALSE,
            client = "", signature = ""))

并且在每一步都遇到了意外的“,”错误。

我也试着写了下面的循环

r <- for(i in 1:10){
  revgeocode(location = ("z$lon", "z$lat"),output = "more", messaging =      FALSE, sensor = FALSE, override_limit = FALSE,client = "", signature = "")}

并得到类似的错误

请提供一些 material 或有用的链接,以帮助我编写反向地理编码循环。如何验证数据的真实性?

基于此 ,您可以在 data.frame

中创建新变量

我们使用 mapply() 处理您的坐标,并 return 列表 res 中的结果。

res <- mapply(FUN = function(lon, lat) { 
  revgeocode(c(lon, lat), output = "more") 
  }, 
  df$lon, df$lat
  )

然后,我们使用 data.table 中的 rbindlist() 将列表转换为 data.frame(使用 fill = TRUE,因为并非 res 的所有元素都具有相同的长度,即一些结果不 return a street_number and a postal_code) and cbind() it to the original data

cbind(df, data.table::rbindlist(res, fill = TRUE))

更新

根据您的评论,如果您想处理 more than 2500 queries,您可以订阅 Google Maps APIs 高级计划以解锁更高的配额。然后,您可以使用 signatureclient 参数将您的凭据传递给 revgeocode()

根据 documentation 中提到的:

Upon purchasing your Google Maps APIs Premium Plan license, you will receive a welcome email from Google that contains your client ID and your private cryptographic key.

Your client ID is used to access the special features of Google Maps APIs Premium Plan. All client IDs begin with a gme- prefix. Pass your client ID as the value of the client parameter. A unique digital signature is generated using your private cryptographic key. Pass this signature as the value of the signature parameter.

您可以通过检查 revgeocode() source 以及 URL 的构造方式来了解它的工作原理:

sensor4url <- paste("&sensor=", sensor, sep = "")
client4url <- paste("&client=", client, sep = "")
signature4url <- paste("&signature=", signature, sep = "")
url_string <- paste("http://maps.googleapis.com/maps/api/geocode/json?latlng=", 
        loc4url, sensor4url, sep = "")
    if (userType == "business") {
        url_string <- paste(url_string, client4url, signature4url, 
            sep = "")
    }

数据

df <- structure(list(lat = c(32.31, 32.19, 34.75, 35.09, 35.35, 34.74 ), lon = 
c(119.827, 119.637, 119.381, 119.364, 119.534, 119.421 )), .Names = 
c("lat", "lon"), row.names = c(21L, 32L, 37L, 48L, 50L, 89L), class = "data.frame") 

我在集成 API 密钥时遇到了 问题。基本上是将 API 键集成到 R 调用的 URL 中。 如果 对您没有帮助,您需要更改核心代码(在 Github 上查找)以允许调用键的参数。