2017-08-16 36 views
-1

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

## 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 
+0

你的问题并不完全清楚。请更新您的问题,以反映发生了什么。如果您想要设法规避Google的局限性,那么您很可能会面临困难。 –

+0

我不打算规避Google的局限性,这就是为什么我需要一个使用我的API密钥的解决方案,所以我将能够每天接收并收到超过2500条结果。抱歉,我不清楚,我认为批量地理编码描述了我的需要;我将获取存储在数据框中的几(千)个地址的纬度和经度坐标。 – user3342735

+1

@TFerrell - 这个问题是针对R包'googleway'的,因此如果您熟悉其中的一个/这两个,则'清楚' – SymbolixAU

回答

2

你已经构建了您的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") 

enter image description here


注:

如果你想成为“肯定”是排队与输入地址坐标,你应该建立,做了的*apply里面你的结果地理编码。

+0

当某些地址无法进行地理编码时,似乎无法正常工作。 – user3342735

+0

@ user3342735你需要实现一些错误处理来解决这个问题。 – SymbolixAU

相关问题