繁体   English   中英

使用googleway R进行批量地理编码

[英]Batch Geocoding with googleway R

我在使用googleway软件包中的google_geocode函数来批处理地理编码时遇到了麻烦。 我想输入一个地址数据框,并为每个地址返回纬度和经度坐标。 地址数量远远超出了Google的每日2500个查询限制,因此该解决方案需要使用API​​密钥来允许购买更多查询。

## Your Google API key
key<-"<insert key here>"
###  Make Data Frame with two observations
Dt<-as.data.frame(matrix(c(" 4605 Langdon ST , Fernley , NV , 89408", -119.2026,
          " 350 Quivera LN , Sparks , NV , 89441", NA), ncol=2)) 
###Change Column Names
colnames(Dt)<-c("address", "longitude")

### Make address column character
Dt$address<-as.character(Dt$address)

### Make data frame with one observation
dt<-Dt[1,]


### geocode one observation with googleway  This Works!!
google_geocode(address = dt[,"address"],
           key = key)  

### batch geocode 
res <- apply(Dt, 1, function(Dt){

google_geocode(address=list(Dt[,"address"]),
              key = key)
})

##  Error in Dt[, "address"] : incorrect number of dimensions

您构造data.frame的方式似乎有些复杂,所以我在这里重新做

dt <- data.frame(address = c("4605 Langdon St, Fernley, NV, 89408", 
                             "350 Quivera Ln, Sparks, NV, 89441"),
                 stringsAsFactors = FALSE)

然后,您可以使用*apply方法对每个地址进行地理编码

library(googleway)

key <- 'api_key'

res <- apply(dt, 1, function(x){
  google_geocode(address = x[['address']],
                 key = key)
})

str(res)
# List of 2
# $ :List of 2
# ..$ results:'data.frame': 1 obs. of  5 variables:
#   .. ..$ address_components:List of 1
# .. .. ..$ :'data.frame':  8 obs. of  3 variables:
#   .. .. .. ..$ long_name : chr [1:8] "4605" "Langdon Street" "Fernley" "Lyon County" ...
# .. .. .. ..$ short_name: chr [1:8] "4605" "Langdon St" "Fernley" "Lyon County" ...
# .. .. .. ..$ types     :List of 8
# .. .. .. .. ..$ : chr "street_number"
# .. .. .. .. ..$ : chr "route"
# ... etc

然后,您可以提取每个结果的坐标,并对其进行任何处理...

coords <- lapply(res, function(x){
  x$results$geometry$location
})

coords <- lapply(seq_along(res), function(x){
  coords <- res[[x]]$results$geometry$location
  address <- dt[x, 'address']
  res_df <- data.frame(lat = coords[, 'lat'],
                       lon = coords[, 'lng'], 
                       address = address
                       )
})

df_coords <- do.call(rbind, coords)
df_coords
#        lat       lon                             address
# 1 39.59275 -119.2026 4605 Langdon St, Fernley, NV, 89408
# 2 39.68911 -119.6345   350 Quivera Ln, Sparks, NV, 89441

mapKey <- symbolix.utils::mapKey()

google_map(key = mapKey) %>%
  add_markers(data = df_coords, lat = "lat", lon = "lon", info_window = "address")

在此处输入图片说明


笔记:

如果您想“确保”坐标与输入地址对齐,则应在进行地理编码的*apply内部构造结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM