设置 Flutter 项目

在设置 Flutter 项目之前,请确保您已完成开始前须知一文中的前提步骤。在启用结算功能并创建 API 密钥后,您便可以设置用于开发应用的 Flutter 项目。

第 1 步:安装所需的软件

若要使用 Flutter 版 Google 地图软件包构建项目,您必须安装 Flutter SDK 并根据您的目标平台设置开发环境。有关详情,请查看 Flutter 安装指南

第 2 步:在新项目中安装 Flutter 版 Google 地图软件包

Flutter 版 Google 地图软件包以插件的形式提供。

创建 Flutter 项目并添加 Google 地图插件。

  1. 使用 `flutter create` 创建一个新的 Flutter 项目:
      flutter create google_maps_in_flutter --platforms=android,ios,web
      
      Creating project google_maps_in_flutter...
      [Listing of created files elided]
      Wrote 127 files.
    
      All done!
    您可在 google_maps_in_flutter/lib/main.dart 中找到相应的应用代码。 若要运行您的应用,请输入:
      cd google_maps_in_flutter
      flutter run
    此应用将以 iOS、Android 和 Web 为目标平台。Google Maps SDK 目前不支持浏览器之外的桌面应用。
  2. 在此项目中添加 Flutter 版 Google 地图软件包插件。
    flutter pub add google_maps_flutter
      
      Resolving dependencies...
      [Listing of dependencies elided]
    
      Changed 14 dependencies!

第 3 步:设置平台版本

Android

设置 Android SDK 的最低版本。

  1. 在您的首选 IDE 中打开 android/app/build.gradle 配置文件。
  2. android.defaultConfig.minSdkVersion 的值更改为 21
      android {
        //...
        defaultConfig {
            applicationId "com.example.google_maps_in_flutter"
            minSdkVersion 21     // Set to 21
            targetSdkVersion flutter.targetSdkVersion
            versionCode flutterVersionCode.toInteger()
            versionName flutterVersionName
        }
        //...
      }
  3. 在配置 defaultConfig 时,指定您自己的唯一 ApplicationID
  4. 保存文件并将项目更改与 Gradle 同步

iOS

设置 iOS 平台的最低版本。

  1. 在您的首选 IDE 中打开 ios/Podfile 配置文件。
  2. 将以下几行内容添加到此 Podfile 的开头:
      # Set platform to 14.0 to enable latest Google Maps SDK
      platform :ios, '14.0'

第 4 步:将您的 API 密钥添加到项目中

您在按开始前须知一文做准备工作时,为自己的应用生成了一个 API 密钥。现在,请将该密钥添加到您的 Flutter 项目中。您应将此 API 密钥添加到 Flutter 项目的所有目标平台:iOS、Android 和 Web。

在下例中,请将 YOUR_API_KEY 替换为您的 API 密钥。

Android

为了简化此任务,建议您使用 Android 版 Secret Gradle 插件

如需在 Google 地图项目中安装 Android 版 Secret Gradle 插件,请执行以下操作:

  1. 在 Android Studio 中,打开顶级 build.gradlebuild.gradle.kts 文件,并将以下代码添加到 buildscript 下的 dependencies 元素中。

    Groovy

    buildscript {
        dependencies {
            classpath "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1"
        }
    }

    Kotlin

    buildscript {
        dependencies {
            classpath("com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1")
        }
    }
    
  2. 打开模块级 build.gradle 文件,并将以下代码添加到 plugins 元素中。

    Groovy

    plugins {
        // ...
        id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    }

    Kotlin

    plugins {
        id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin")
    }
  3. 在模块级 build.gradle 文件中,请务必将 targetSdkcompileSdk 设置为 34。
  4. 保存文件并将项目与 Gradle 同步
  5. 在顶级目录中打开 secrets.properties 文件,然后添加以下代码。将 YOUR_API_KEY 替换为您的 API 密钥。secrets.properties 不会签入版本控制系统,因此请将您的密钥存储在此文件中。
    MAPS_API_KEY=YOUR_API_KEY
  6. 保存文件。
  7. 在顶级目录(即 secrets.properties 文件所在的文件夹)中创建 local.defaults.properties 文件,然后添加以下代码。

    MAPS_API_KEY=DEFAULT_API_KEY

    此文件的作用是为 API 密钥提供备用位置,以免在找不到 secrets.properties 文件的情况下构建失败。如果您是从省略 secrets.properties 的版本控制系统中克隆应用,而您还没有在本地创建 secrets.properties 文件来提供 API 密钥,就可能会出现上述情况。

  8. 保存文件。
  9. AndroidManifest.xml 文件中,定位到 com.google.android.geo.API_KEY 并更新 android:value attribute。如果 <meta-data> 标记不存在,请创建该标记作为 <application> 标记的子标记。
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="${MAPS_API_KEY}" />

    Note: com.google.android.geo.API_KEY is the recommended metadata name for the API key. A key with this name can be used to authenticate to multiple Google Maps-based APIs on the Android platform, including the Flutter SDK. For backwards compatibility, the API also supports the name com.google.android.maps.v2.API_KEY. This legacy name allows authentication to the Android Maps API v2 only. An application can specify only one of the API key metadata names. If both are specified, the API throws an exception.

  10. In Android Studio, open your module-level build.gradle or build.gradle.kts file and edit the secrets property. If the secrets property does not exist, add it.

    Edit the properties of the plugin to set propertiesFileName to secrets.properties, set defaultPropertiesFileName to local.defaults.properties, and set any other properties.

    Groovy

    secrets {
        // Optionally specify a different file name containing your secrets.
        // The plugin defaults to "local.properties"
        propertiesFileName = "secrets.properties"
    
        // A properties file containing default secret values. This file can be
        // checked in version control.
        defaultPropertiesFileName = "local.defaults.properties"
    
        // Configure which keys should be ignored by the plugin by providing regular expressions.
        // "sdk.dir" is ignored by default.
        ignoreList.add("keyToIgnore") // Ignore the key "keyToIgnore"
        ignoreList.add("sdk.*")       // Ignore all keys matching the regexp "sdk.*"
    }
            

Kotlin

secrets {
    // Optionally specify a different file name containing your secrets.
    // The plugin defaults to "local.properties"
    propertiesFileName = "secrets.properties"

    // A properties file containing default secret values. This file can be
    // checked in version control.
    defaultPropertiesFileName = "local.defaults.properties"

    // Configure which keys should be ignored by the plugin by providing regular expressions.
    // "sdk.dir" is ignored by default.
    ignoreList.add("keyToIgnore") // Ignore the key "keyToIgnore"
    ignoreList.add("sdk.*")       // Ignore all keys matching the regexp "sdk.*"
}
        

注意:如上所示,建议使用 com.google.android.geo.API_KEY 作为 API 密钥的元数据名称。采用该名称的密钥可用来接受 Android 平台上多个基于 Google 地图的 API(包括 Flutter SDK)的身份验证。为了实现向后兼容性,API 还支持使用 com.google.android.maps.v2.API_KEY 作为名称。但使用该旧名称时,密钥只能接受 Android Maps API v2 的身份验证。应用只能指定其中一个 API 密钥元数据名称。如果两个都指定,API 会抛出异常。

iOS

将您的 API 密钥添加到 AppDelegate.swift 文件中。

  1. 使用您的首选 IDE 打开 Flutter 项目中的 ios/Runner/AppDelegate.swift 文件。
  2. 添加以下导入语句,将 Flutter 版 Google 地图软件包添加到您的应用中:
  3. import GoogleMaps
  4. 将您的 API 添加到 application(_:didFinishLaunchingWithOptions:) 方法,将其中的 YOUR_API_KEY 替换为您的 API 密钥:
    GMSServices.provideAPIKey("YOUR_API_KEY")
  5. 保存并关闭 AppDelegate.swift 文件。

完成的 AppDelegate.swift 文件应与以下内容类似:

import UIKit
import Flutter
import GoogleMaps  // Add this import

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)

    // TODO: Add your Google Maps API key
    GMSServices.provideAPIKey("YOUR_API_KEY")

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Web

将您的 API 密钥添加到 index.html 应用文件中。

  1. 使用您的首选 IDE 打开 Flutter 项目中的 web/index.html 文件。
  2. <head> 标记中添加以下脚本标记(将其中的 YOUR_API_KEY 替换为您的 API 密钥)。
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
  3. 保存并关闭 index.html 文件。

    index.html 中的完整 head 部分应与以下内容类似:

        <head>
          <base href="/">
          
          <meta charset="UTF-8">
          <meta content="IE=Edge" http-equiv="X-UA-Compatible">
          <meta name="description" content="A new Flutter project.">
          
          <!-- iOS meta tags & icons -->
          <meta name="apple-mobile-web-app-capable" content="yes">
          <meta name="apple-mobile-web-app-status-bar-style" content="black">
          <meta name="apple-mobile-web-app-title" content="google_maps_in_flutter">
          <link rel="apple-touch-icon" href="icons/Icon-192.png">
          
          <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY">
          </script>
          
          <title>google_maps_in_flutter</title>
          <link rel="manifest" href="manifest.json">
        </head>

第 5 步:添加地图

以下代码展示了如何在新的 Flutter 应用中添加简单的地图。

  1. 使用您的首选 IDE 打开 Flutter 项目中的 lib/main.dart 文件。
  2. 在应用的默认主方法中添加或更新方法,以创建和初始化 mapController 的实例。
          import 'package:flutter/material.dart';
          import 'package:google_maps_flutter/google_maps_flutter.dart';
          
          void main() => runApp(const MyApp());
          
          class MyApp extends StatefulWidget {
            const MyApp({super.key});
          
            @override
            State createState() => _MyAppState();
          }
          
          class _MyAppState extends State {
            late GoogleMapController mapController;
          
            final LatLng _center = const LatLng(-33.86, 151.20);
          
            void _onMapCreated(GoogleMapController controller) {
              mapController = controller;
            }
          
            @override
            Widget build(BuildContext context) {
              return MaterialApp(
                home: Scaffold(
                  appBar: AppBar(
                    title: const Text('Maps Sample App'),
                    backgroundColor: Colors.green[700],
                  ),
                  body: GoogleMap(
                    onMapCreated: _onMapCreated,
                    initialCameraPosition: CameraPosition(
                      target: _center,
                      zoom: 11.0,
                    ),
                  ),
                ),
              );
            }
          }
  3. 启动您要用于运行应用的模拟器或设备。
  4. 运行应用。您看到的输出应该会类似于:
      flutter run
    
       
        Multiple devices found:
        Android phone (mobile) • emulator-5554 • android-arm64  • Android 13 (API 33) (emulator)
        iPhone (mobile)  • ios • com.apple.CoreSimulator.SimRuntime.iOS-16-2 (simulator)
        Chrome (web) • chrome • web-javascript • Google Chrome 108.0.5359.124
        [1]: Android phone
        [2]: iPhone
        [3]: Chrome
        
        Please choose one (To quit, press "q/Q"): 

    键入您要运行的平台所对应的编号。每次您调用 flutter run 时,Flutter 都会向您显示这些平台选项。如果您的开发系统没有正在运行的模拟器或已连接的测试设备,Flutter 会选择打开 Chrome。

    每个平台都应显示一张以澳大利亚悉尼为中心的地图。如果该地图没有显示,请检查您是否已将 API 密钥添加到相应的目标项目中。

后续步骤

现在,您已经有了 API 密钥和 Flutter 项目,接下来便可以创建和运行应用了。Flutter 版 Google 地图软件包提供了许多教程和示例应用,可帮助您快速入门。如需了解详情,请查看以下资源: