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

使用google_places循环DataFrame时遇位置参数验证错误求助

问题解决方法

错误原因分析

  • 位置参数传递错误:你用c(df$Latitude, df$Longitude)会把所有行的经纬度拼接成一个超长向量,而google_places()要求location是单个长度为2的向量(一组纬度+经度)。
  • 语法错误:代码中google_places(...)后面多了一个右括号,导致search_string等参数不在函数调用范围内,语法不合法。

修正后的代码

基础修正版(解决报错)

set_key("your_api_key")

# 遍历每行,传递对应行的经纬度对
results_list <- lapply(1:nrow(df), function(x){
  google_places(
    location = c(df$Latitude[x], df$Longitude[x]),  # 取当前行的经纬度
    search_string = 'Coffee Shop',
    radius = 5000,
    rankby = "distance"  # 可选:按距离排序,方便筛选最近的场所
  )
})

进阶版:提取结果并整理为DataFrame

如果要把所有结果合并成结构化的DataFrame(参考你提到的google_distance转DataFrame的思路),可以进一步处理:

library(dplyr)

# 定义函数提取单条查询的场所信息
extract_place_info <- function(place_result) {
  if(is.null(place_result$results)) return(NULL)
  
  place_data <- place_result$results %>%
    select(name, formatted_address, geometry$location$lat, geometry$location$lng, rating, user_ratings_total) %>%
    rename(
      place_lat = `geometry$location$lat`,
      place_lng = `geometry$location$lng`
    )
  
  # 添加原始查询的经纬度,方便关联
  place_data$query_lat <- place_result$location[1]
  place_data$query_lng <- place_result$location[2]
  
  return(place_data)
}

# 批量提取并合并所有结果
all_places_df <- bind_rows(lapply(results_list, extract_place_info))

# 每个查询位置只保留前20个场所
all_places_top20 <- all_places_df %>%
  group_by(query_lat, query_lng) %>%
  slice_head(n = 20) %>%
  ungroup()

额外注意事项

  • API配额限制:150个位置各调用一次API,需注意Google Places API的调用配额,避免超出限制导致请求失败。
  • 分页处理:如果某个位置半径内的咖啡店超过20个,默认返回前20个;若需更多结果,可通过page_token参数实现分页查询。

内容的提问来源于stack exchange,提问作者Normandie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 17:17:02