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

使用R绘制香港底图失败求助:附代码及报错信息

Fixing the ggmap Error When Fetching Hong Kong Map

Hey there! I can see you're having trouble pulling up a Hong Kong map with ggmap—let's break down what's going wrong and fix it.

What's Causing the Error?

The error you're seeing related to data.frame(ll.lat = ll[1], ...) usually happens when ggmap can't successfully retrieve the map boundaries from Google. This is almost always tied to issues with your API key setup or redundant/invalid parameters in your get_map() call.

Step-by-Step Fixes

1. Clean Up Redundant Parameters

Your force = ifelse(source == "google", TRUE, TRUE) line is unnecessary—since you're explicitly setting source = "google", you can just set force = TRUE directly. This simplifies your code and avoids potential parameter parsing bugs.

2. Properly Set Up Google API Key

Google Maps Static API now requires a valid API key (with the API enabled in your Google Cloud Console) to work with ggmap. Here's how to fix this:

  • First, make sure you have a Google Cloud account, created a project, enabled the Google Maps Static API, and generated an API key.
  • Register your key in R before calling get_map() using register_google():
library(ggmap)
library(ggplot2)

# Replace with your actual Google API key
register_google(key = "your_google_api_key_here")

# Fetch the Hong Kong map with simplified parameters
hk_map <- get_map(
  location = "Hong Kong",
  zoom = 10,
  scale = 2,
  maptype = "roadmap",
  source = "google",
  force = TRUE,
  messaging = FALSE,
  filename = "ggmapTemp",
  crop = TRUE,
  color = "color",
  language = "en-EN"
)

# Plot the map
ggmap(hk_map)

3. Test with a Non-Google Source (No API Key Needed)

If you don't want to deal with Google's API setup right now, try using Stamen maps instead—they don't require an API key:

hk_map_stamen <- get_map(
  location = "Hong Kong",
  zoom = 10,
  maptype = "toner", # You can also use "terrain" or "watercolor"
  source = "stamen"
)

ggmap(hk_map_stamen)

Additional Checks

  • If you still get errors with Google, double-check that your API key is correctly entered, the Google Maps Static API is enabled in your Cloud Console, and you haven't hit your API quota limits.
  • Ensure you're using the latest version of ggmap (run update.packages("ggmap") if needed) since older versions have different Google API handling.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:07:22