从Google地图中获取r中的位置列表



我使用google_placesgoogleway包从谷歌获得位置的数据框架。我正在寻找"在德国献血"。(德文)https://www.google.de/maps/search/Blutspende+in+Deutschland/@51.5019637,6.4650438,12z小插图说每个API查询结果在20个位置。https://cran.r-project.org/web/packages/googleway/vignettes/googleway-vignette.html我想德国应该有大约300个献血地点。我试图建立一个循环,返回所有谷歌的地方结果到我的关键字的数据框架。类似的帖子可以在这里找到next_page_token在第二次尝试时不工作(google_places函数)

我怎样才能建立我的循环,使它返回所有谷歌搜索的数据框架?

library(googleway)
# initialize list
datalist = list()
# start first search
key = "YOUR-KEY"
res <- google_places(search_string = "Blutspende in Deutschland",
key = key)
# store first 20 results
datalist[[1]] <- data.frame(Name = res$results$name,
Place = res$results$formatted_address)
# set next page token
token = res$next_page_token
for(i in 1:10){
# sleep time
Sys.sleep(2)

# next search 
res_n <- google_places(search_string = "Blutspende in Deutschland",
page_token  = token,
key = key)

# store next results  
datalist[[i+1]] <- data.frame(Name = res_n$results$name,
Place = res_n$results$formatted_address)

# set next token again  
token <- res_n$next_page_token

# print status   
aa = res_n$status
cat(i, aa, 'n')
}
# to dataframe
big_data = do.call(rbind, datalist)

在这个搜索中有大量的重复。

library(tidyverse)
big_data %>% distinct() %>% nrow()

对我来说,202个条目中有54个不同的条目。我不知道为什么。

Google Map的位置API通过查询将响应限制为60个位置,最多可分页3个json,其中包含20个位置。(参见Places API文档)。

要获得超过60个观测值,googleway的一个简单技巧是按地区/土地,甚至按市政当局进行查询。在下一个示例中,我将循环遍历16个德国地区/州,以获得600多个结果。

library(tidyverse)
library(googleway)
key   <- "your_api_key"
land <- c("Baden-Württemberg", "Bayern", "Berlin", "Brandenburg", "Bremen", "Hamburg", "Hessen", "Mecklenburg-Vorpommern", "Niedersachsen", "Nordrhein-Westfalen", "Rheinland-Pfalz", "Saarland", "Sachsen", "Sachsen-Anhalt", "Schleswig-Holstein", "Thüringen")
queries <- paste0("Blutspende Blutbank in ", land, ", Deutschland")
# A custom loop function for google_places() 
google_places_loop <- function(search_string, key, ntimes = 3, page_token = "") {
print(search_string)    
iter <- 0
obj_df <- tibble()

while(iter < ntimes & !is.null(page_token)) {
iter <- iter + 1
print(iter)
obj_response <- google_places(search_string = search_string, key = key, page_token = page_token,
language = "DE", # Optional, but note that setting language to German might get you a few more locations
)
obj_df_new <-   as_tibble(obj_response$results) %>% mutate(iter = iter)
obj_df <- bind_rows(obj_df, obj_df_new)
page_token <- obj_response$next_page_token

if(is.null(page_token) == TRUE) {
print("No more pagination tokens")
Sys.sleep(2)
} else {
Sys.sleep(3) 
}
}

obj_df

}
# Finally, we loop through the queries by the custom function.
df_blutspende <- map_df(.x = queries, .f = google_places_loop, key = key)

最新更新