You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

googleway包遍历坐标调用Google Maps API绕60结果限制报错排查

问题根源

你的批量查询代码无法运行,是3个核心逻辑错误导致的:

  • 坐标传参格式错误:你从txt读入的coords列是拼接好的"纬度, 经度"格式字符串,但google_places()的location参数要求传入长度为2的数值向量,按顺序对应纬度、经度,直接传字符串接口无法识别坐标位置。
  • 结果存储逻辑错误:for循环内每次查询完都直接把结果赋值给df变量,后一次查询会直接覆盖前一次的结果,循环结束后你只能拿到最后一个质心点的查询数据,之前所有格网的结果都会丢失。
  • 代码结构冗余错误:你把format_res()、do_search()、full_search()三个工具函数的定义全写在了for循环内部,每次遍历坐标都会重复定义一次函数,不仅运行效率低,还容易触发R的环境作用域报错。
修正后完整代码

首先调整坐标文件读取逻辑,把字符串拆成单独的经纬度数值列,再把工具函数定义移到循环外面,最后用列表存每个坐标的查询结果,循环结束后一次性拼接去重即可:

### 加载依赖包
library(tidyverse)
library(googleway)

### 固定查询参数配置
place_type <- "store" 
key <- "替换成你自己的Google Maps API Key" 
radius <- 100 

### 定义工具函数(移到循环外,只定义一次)
format_res <- function(res) {
  setNames(
    cbind(
      googleway::access_result(res, "coordinates"),
      googleway::access_result(res, "place_name")
    )
    , c("lat", "long", "name")
  )
}

do_search <- function(place_type, key, location, radius, page_token = NULL) {
  google_places(
    place_type = place_type,
    location = location,
    key = key,
    radius = radius,
    page_token = page_token
  )
}

full_search <- function(place_type, key, location, radius) {
  counter <- 0
  page_token <- NULL
  is_another_page <- TRUE
  df <- NULL # 初始化空对象存结果,避免无返回值时报错
  
  while(is_another_page) {
    res <- do_search(place_type, key, location, radius, page_token)
    if(res$status == "OK") {
      if(counter == 0) {
        df <- format_res(res)
      } else {
        df <- rbind(df, format_res(res))
      }
      counter <- counter + 1
    }
    page_token <- res[["next_page_token"]]
    is_another_page <- !is.null(page_token)
    Sys.sleep(3) # 遵守接口调用频率限制
  }
  return(df)
}

### 读取并处理坐标文件
dfCoords <- read.csv("~/coords.txt", sep="") %>%
  # 把"纬度,经度"格式的字符串拆成两个数值列
  separate(col = coords, into = c("lat", "lng"), sep = ", ", convert = TRUE)

### 初始化结果存储列表
res_list <- vector(mode = "list", length = nrow(dfCoords))

### 批量遍历查询
for (i in 1:nrow(dfCoords)) {
  # 提取当前行的经纬度,组装成接口要求的数值向量
  current_loc <- c(dfCoords$lat[i], dfCoords$lng[i])
  # 执行查询,结果存入列表对应位置
  res_list[[i]] <- full_search(
    place_type = place_type,
    key = key,
    location = current_loc,
    radius = radius
  )
  # 打印查询进度
  cat("已完成第", i, "个坐标查询,共", nrow(dfCoords), "个\n")
}

### 拼接所有结果并去重(相邻格网可能搜到同一个POI)
final_df <- bind_rows(res_list) %>%
  distinct(across(c(lat, long, name)), .keep_all = TRUE)

### 查看结果结构
str(final_df)
方案思路示意图

六边形格网分块检索POI方案示意图

注意事项
  • 请确保你的Google Maps API Key已经开通了Places API权限,且账户有足够的调用额度,六边形格网切分越细,调用次数越多,注意控制成本。
  • 接口要求两次请求间隔至少2秒,代码里保留了Sys.sleep(3)的设置,不要随意删除,否则会触发接口频率限制报错。
  • 相邻六边形格网的100m搜索半径会有重叠区域,最后拼接结果时一定要按POI的名称、经纬度做去重,避免重复统计。

内容的提问来源于stack exchange,提问作者Neri David Martinez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 11:21:43