2017-08-16 111 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