如果我使用您问题中的地址,API 对我有用。但是,使用your other question 中的地址会给我一个ZERO_RESULTS 回报。
我们可以在gsub() 命令中使用简单的正则表达式删除最后一个空格之后的地址的最后一部分。
library(googleway)
set_key("your_api_key")
## invalid query
add <- "대한민국 경기도 안산시 단원구 성곡동 강촌로 140"
res <- google_geocode(address = add, language = "kr")
res
# $results
# list()
#
# $status
# [1] "ZERO_RESULTS"
## remove the last part after the final space and it works
new_add <- gsub(' \\S*$', '', add)
res <- google_geocode(address = new_add, language = "kr")
geocode_coordinates(res)
# lat lng
# 1 37.31737 126.7672
您可以将其转换为一个迭代循环,该循环将继续删除最后一个“空格”字符之后的所有内容,并尝试对新地址进行地理编码。
## the curl_proxy argument is optional / specific for this scenario
geocode_iterate <- function(address, curl_proxy) {
continue <- TRUE
iterator <- 1
while (continue) {
print(paste0("attempt ", iterator))
print(address)
iterator <- iterator + 1
res <- google_geocode(address = address, language = "kr", curl_proxy = curl_proxy)
address <- gsub(' \\S*$', '', address)
if (res[['status']] == "OK" | length(add) == 0 | grepl(" ", add) == FALSE ){
continue <- FALSE
}
}
return(res)
}
add <- "대한민국 경기도 안산시 단원구 성곡동 강촌로 140"
res <- geocode_iterate(address = add, curl_proxy = curl_proxy)
# [1] "attempt 1"
# [1] "대한민국 경기도 안산시 단원구 성곡동 강촌로 140"
# [1] "attempt 2"
# [1] "대한민국 경기도 안산시 단원구 성곡동 강촌로"
小心确保while 循环能够真正退出。您不想进入无限循环。
请记住,即使返回了 ZERO_RESULTS,该查询仍会计入您的每日 API 配额。