1. 简介
Flutter 是 Google 的界面工具包,用于通过单一代码库在移动设备、Web 和桌面设备上打造优质体验。
借助 google_maps_flutter 插件,您可以将由 Google 地图数据提供支持的互动式地图直接嵌入到 Flutter 应用中。该插件会自动处理对 Google 地图服务器的访问、地图渲染以及用户手势(例如点按、拖动和双指张合缩放)。您还可以在地图上叠加标记和信息窗口,以突出显示地点并让用户与地图数据互动。
构建内容
在此 Codelab 中,您将与 Google Antigravity 协作,以迭代方式构建一个包含互动式 Google 地图的 Flutter 应用。
完成后的应用将:
|
|
您的学习之旅
此 Codelab 将指导您逐步构建 Google 地图应用:
- 设置 Flutter 环境 - 配置 Flutter SDK、Google Antigravity 以及目标设备或浏览器。
- 创建项目 - 提示 Antigravity 使用
google_maps_flutter和material_ui构建 Flutter 项目,并配置平台设置。 - 向应用添加 Google 地图 - 为 Android、iOS 和 Web 配置 Google Maps Platform API 密钥,并渲染以波特兰为中心的初始
GoogleMap。 - 在地图上显示 Google 办公地点 - 使用
json_serializable对 JSON 资源中的 Google 办公地点进行建模和反序列化,并在地图上显示互动式标记。
学习内容
- 如何与 Google Antigravity 协作,以迭代方式构建和自定义 Google 地图 Flutter 应用。
- 如何为 Android、iOS 和 Web 配置
google_maps_flutter插件和平台 API 密钥。 - 如何嵌入
GoogleMapwidget 并控制其初始相机位置。 - 如何使用
json_serializable解析 JSON 位置数据,并在地图上呈现Marker叠加层。
前提条件
- 基本熟悉 Flutter widget 和 Dart 语法。
- Google Maps Platform API 密钥(对于本地开发测试,此密钥为可选;若要呈现不带水印的地图图块,则必须提供此密钥)。
您想通过此 Codelab 学习哪些内容?
2. 设置您的 Flutter 环境
编辑者
此 Codelab 使用 Google Antigravity 作为 AI 优先的开发环境。在每个步骤中,您都需要提示 Antigravity 生成或改进应用的代码,查看生成的文件中的关键 Flutter 和 Google 地图概念,并可选择探索创意变体。
选择目标开发平台
您可以使用以下任意目标运行此 Codelab:
- 一台连接到计算机并设置为开发者模式的实体 Android 或 iOS 设备。
- iOS 模拟器(需要在 macOS 上安装 Xcode)。
- Android 模拟器(需要在 Android Studio 中设置)。
- 网络浏览器,例如 Chrome。
安装 Flutter
如需获取关于如何安装 Flutter SDK 的最新说明,请随时访问 docs.flutter.dev。
对于此 Codelab,请安装以下软件:
- Flutter SDK
- 已启用官方 Dart 和 Flutter 插件的 Google Antigravity(可在插件市场的 Build with Google 部分找到)。
- 您选择的目标开发平台所需的平台工具(例如,iOS 平台需要 Xcode,Android 平台需要 Android Studio,Web 平台需要 Chrome)。
3. 创建项目
提示 Antigravity 创建项目
- 启动 Google Antigravity,然后打开一个空目录,您希望在该目录中构建项目(选择不需要提权或不包含空格的路径,例如主目录或
C:\src\中的文件夹)。 - 在 Antigravity 智能体对话面板中,发送以下提示,以搭建 Flutter 项目、添加所需的软件包并配置平台设置:
Create a new Flutter project named `google_maps_in_flutter` in the current directory targeting Android, iOS, and web (`--platforms android,ios,web`). Add the `google_maps_flutter` and `material_ui` packages, update `lib/main.dart` and `test/widget_test.dart` to import `package:material_ui/material_ui.dart` instead of `package:flutter/material.dart`, and set the minimum iOS platform version in `ios/Podfile` to `platform :ios, '16.0'`.
了解生成的配置
Antigravity 会为 Android、iOS 和 Web 创建 google_maps_in_flutter 项目,将 google_maps_flutter 和 material_ui 添加到 pubspec.yaml,并配置平台项目文件。
配置 iOS platform 版本
Google Maps SDK for iOS 要求最低部署目标为 iOS 16.0(请参阅 Google Maps Flutter 软件包配置指南)。Antigravity 会更新 ios/Podfile 的顶部,以声明 platform :ios, '16.0':
# Google Maps SDK for iOS requires iOS 16.0
# https://developers.google.com/maps/flutter-package/config#ios
platform :ios, '16.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
Android minSdk 配置
Google Maps SDK for Android 需要 minSdk 21 或更高版本。现代 Flutter 模板会在 android/app/build.gradle.kts 中配置 minSdk = flutter.minSdkVersion(默认为 Android API 24 或更高版本),因此 Android 开箱即满足最低 SDK 要求。
4. 将 Google 地图添加到应用
获取 Google Maps Platform API 密钥
如需在 Flutter 应用中显示已发布的地图图块,请使用 Google Maps Platform 配置 API 项目,并按照目标平台的设置指南生成 API 密钥:
提示 Antigravity 配置 API 密钥并显示地图
准备好 API 密钥(或在开发过程中使用占位符密钥)后,在 Antigravity 智能体对话面板中发送以下提示,以关联平台 API 密钥条目并显示以俄勒冈州波特兰为中心的 Google 地图:
Configure the project for Google Maps and display an initial map on the screen:
1. Add Google Maps API key configuration entries to `android/app/src/main/AndroidManifest.xml` (`com.google.android.geo.API_KEY` with value `YOUR-KEY-HERE`), `ios/Runner/AppDelegate.swift` (`import GoogleMaps` and `GMSServices.provideAPIKey("YOUR-API-KEY")` inside `didInitializeImplicitFlutterEngine`), and `web/index.html` (`<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-KEY-HERE"></script>`).
2. Update `lib/main.dart` (importing `package:material_ui/material_ui.dart` and `package:google_maps_flutter/google_maps_flutter.dart`) so `MyApp` is a `StatefulWidget` with `ThemeData(colorSchemeSeed: Colors.green[700])`, an `AppBar` titled `'Maps Sample App'` with `elevation: 2`, and a `GoogleMap` widget centered on Portland (`LatLng(45.521563, -122.677433)`) with zoom `11.0` and an `_onMapCreated` callback that stores the `GoogleMapController`. Also update `test/widget_test.dart` with a basic widget test that pumps `const MyApp()`.
了解生成的代码
平台 API 密钥注册
每个目标平台都会从其平台专用入口点加载 Google 地图 API 密钥。将 YOUR-KEY-HERE 或 YOUR-API-KEY 替换为您的实际 Google Maps Platform API 密钥:
- Android (
android/app/src/main/AndroidManifest.xml):在标记内注册元素:
<application
android:label="google_maps_in_flutter"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<!-- Add your Google Maps API key here -->
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="YOUR-KEY-HERE"/>
- iOS (
ios/Runner/AppDelegate.swift):导入GoogleMaps模块,并在 Flutter 引擎初始化时将 API 密钥传递给GMSServices.provideAPIKey(_:):
import Flutter
import UIKit
import GoogleMaps
@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
// Add your Google Maps API key here
GMSServices.provideAPIKey("YOUR-API-KEY")
}
}
- Web (
web/index.html):在元素内加载 Maps JavaScript API 脚本:
<!-- Add your Google Maps API key here -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-KEY-HERE"></script>
呈现 GoogleMap 微件 (lib/main.dart)
在 lib/main.dart 中,_MyAppState 会在 Scaffold 内嵌入 GoogleMap widget,并在地图视图初始化后捕获 GoogleMapController:
class _MyAppState extends State<MyApp> {
late GoogleMapController mapController;
final LatLng _center = const LatLng(45.521563, -122.677433);
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(colorSchemeSeed: Colors.green[700]),
home: Scaffold(
appBar: AppBar(title: const Text('Maps Sample App'), elevation: 2),
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(target: _center, zoom: 11.0),
),
),
);
}
}
CameraPosition:定义地图镜头最初指向的位置 (target) 以及缩放程度(zoom: 11.0显示城市级视图)。onMapCreated:在平台地图视图准备就绪时调用,提供一个GoogleMapController,您可以使用它以编程方式平移、缩放或查询地图。
运行并测试应用
由于此步骤会修改平台配置文件(AndroidManifest.xml、AppDelegate.swift 和 web/index.html),因此请在目标设备或模拟器上执行完整运行(而非热重载):
flutter run
您应该会看到一个以俄勒冈州波特兰为中心的互动式地图:
|
|
5. 将 Google 办公地点添加到地图上
Google 在世界各地设立了众多办事处,包括北美洲、拉丁美洲、欧洲、亚太地区以及非洲和中东地区。在此步骤中,您将提示 Antigravity 创建一个包含 Google 办公室坐标、地址和区域的捆绑 assets/locations.json 数据集,使用 json_serializable 和 build_runner 生成强类型 JSON 序列化类,并在地图上将每个办公室显示为交互式 Marker。
提示 Antigravity 加载并显示 Google 办公室标记
在 Antigravity 智能体对话面板中发送以下提示:
Display Google office locations from a bundled JSON asset as markers on the map:
1. Add the `json_annotation` and `json_serializable` packages, plus `build_runner` as a dev dependency (`dev:build_runner`).
2. Create `assets/locations.json` containing a JSON object with `offices` (a list of Google offices around the world, each with `id`, `name`, `address`, `lat`, `lng`, `phone`, `image`, and `region`) and `regions` (each with `id`, `name`, `zoom`, and `coords` containing `lat` and `lng`), and register `assets/locations.json` under the `flutter:` `assets:` section of `pubspec.yaml`.
3. Create `lib/src/locations.dart` with `@JsonSerializable()` classes `LatLng`, `Region`, `Office`, and `Locations` (using `part 'locations.g.dart';`), and a `Future<Locations> getGoogleOffices()` function that loads `'assets/locations.json'` from `rootBundle` and decodes it with `Locations.fromJson`. Run `dart run build_runner build` to generate `lib/src/locations.g.dart`.
4. Update `lib/main.dart` (importing `'src/locations.dart' as locations;`) so `_MyAppState` stores `final Map<String, Marker> _markers = {};`, loads `locations.getGoogleOffices()` in `_onMapCreated`, populates `_markers` inside `setState()` with a `Marker` for each office (using `MarkerId(office.name)`, `LatLng(office.lat, office.lng)`, and `InfoWindow(title: office.name, snippet: office.address)`), updates the `AppBar` title to `'Google Office Locations'`, sets `initialCameraPosition` to `const CameraPosition(target: LatLng(0, 0), zoom: 2)`, and passes `markers: _markers.values.toSet()` to `GoogleMap`.
了解生成的代码
JSON 数据建模和代码生成 (lib/src/locations.dart)
lib/src/locations.dart 不会从非类型化 Map 结构中手动提取字段,而是使用 @JsonSerializable() 为强类型 Dart 类添加注解,并将序列化样板代码委托给 locations.g.dart(由 dart run build_runner build 生成):
@JsonSerializable()
class Office {
Office({
required this.address,
required this.id,
required this.image,
required this.lat,
required this.lng,
required this.name,
required this.phone,
required this.region,
});
factory Office.fromJson(Map<String, dynamic> json) => _$OfficeFromJson(json);
Map<String, dynamic> toJson() => _$OfficeToJson(this);
final String address;
final String id;
final String image;
final double lat;
final double lng;
final String name;
final String phone;
final String region;
}
正在加载捆绑的 JSON 资源 (getGoogleOffices)
在 lib/src/locations.dart 中,getGoogleOffices() 通过 Flutter 的 rootBundle 读取捆绑的 assets/locations.json 文件,并将 JSON 映射反序列化为 Locations 实例:
Future<Locations> getGoogleOffices() async {
return Locations.fromJson(
json.decode(await rootBundle.loadString('assets/locations.json'))
as Map<String, dynamic>,
);
}
在GoogleMap (lib/main.dart) 上填充Marker
在 lib/main.dart 中,_onMapCreated 会等待 locations.getGoogleOffices(),并将每个 Office 转换为 setState() 内的 Marker:
class _MyAppState extends State<MyApp> {
final Map<String, Marker> _markers = {};
Future<void> _onMapCreated(GoogleMapController controller) async {
final googleOffices = await locations.getGoogleOffices();
setState(() {
_markers.clear();
for (final office in googleOffices.offices) {
final marker = Marker(
markerId: MarkerId(office.name),
position: LatLng(office.lat, office.lng),
infoWindow: InfoWindow(title: office.name, snippet: office.address),
);
_markers[office.name] = marker;
}
});
}
import 'src/locations.dart' as locations;:为locations.dart库添加前缀,使其LatLng模型类不会与package:google_maps_flutter/google_maps_flutter.dart中的LatLng发生冲突。Marker和InfoWindow:每个标记都有一个唯一的MarkerId、一个地理position,以及一个在点按时显示办公室name和address的InfoWindow。markers: _markers.values.toSet():调用setState()会触发重新构建,并将更新后的Set传递给GoogleMapwidget,以便图钉显示在全球各地。
运行并测试应用
执行热重启(或重新运行 flutter run,以便加载新添加的 assets/locations.json 软件包)。缩小或平移地球仪,然后点按任意图钉即可查看 Google 办公室的名称和地址:

6. 恭喜!
您已完成此 Codelab,并构建了一个 Flutter 应用,该应用可显示一个填充了 JSON 位置数据的互动式 Google 地图!
您构建的内容
- 使用
google_maps_flutter和material_ui配置了多平台 Flutter 应用。 - 为 Android、iOS 和 Web 设置 Google Maps Platform API 密钥。
- 使用
json_serializable、build_runner和rootBundle资源创建了类型化 JSON 数据层。 - 为全球各地的 Google 办事处渲染了交互式
Marker图钉和InfoWindow弹出式窗口。

