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

如何修改R代码通过Google API生成100个城市随机经纬度点?

生成柏林100个随机经纬度点的R代码修改方案

方案1:基于大致经纬度范围快速生成

直接利用柏林的已知经纬度范围生成随机点,无需调用Google API,高效且满足需求:

# 加载必要包(移除不需要的冗余包)
library(mapview)
library(tidyverse)
library(sf)

# 定义柏林的经纬度范围(可根据需求微调精度)
lat_min <- 52.35
lat_max <- 52.65
lng_min <- 13.2
lng_max <- 13.6

# 生成100个随机经纬度点,设置种子保证结果可重复
set.seed(123)
random_points <- tibble(
  lat = runif(100, min = lat_min, max = lat_max),
  lng = runif(100, min = lng_min, max = lng_max)
)

# 转换为sf格式(可选,方便后续空间分析操作)
random_sf <- st_as_sf(random_points, coords = c("lng", "lat"), crs = 4326)

# 用mapview可视化结果
mapview(random_sf, crs = 4326)

方案2:基于柏林行政边界精准生成(需Google API)

如果需要确保点严格落在柏林行政区域内,可通过Google Geocoding API获取城市边界,再在边界内生成随机点:

library(googleway)
library(mapview)
library(tidyverse)
library(sf)

# 替换为你的Google API密钥
api_key <- "MY_API"

# 获取柏林的行政边界多边形
berlin_geo <- google_geocode(address = "Berlin, Germany", key = api_key)
berlin_poly <- st_as_sf(
  x = berlin_geo$results$geometry$location_type,
  wkt = berlin_geo$results$geometry$polygon,
  crs = 4326
)

# 在柏林边界内生成100个随机点
set.seed(123)
random_points_berlin <- st_sample(berlin_poly, size = 100, type = "random") %>%
  st_as_sf() %>%
  rename(geometry = x) %>%
  mutate(
    lat = st_coordinates(.)[,2],
    lng = st_coordinates(.)[,1]
  )

# 可视化精准生成的随机点
mapview(random_points_berlin, crs = 4326)

关键说明

  • 原代码中的google_places用于搜索特定POI(如披萨店),不适合生成随机点,因此替换为随机数生成或空间采样逻辑
  • 方案1无需API调用,适合快速生成,更换其他大城市只需修改对应的经纬度范围即可
  • 方案2依赖Google Geocoding API,能保证点严格在城市边界内,但会消耗API配额

内容的提问来源于stack exchange,提问作者Simen Fjælberg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:25:17