本頁說明如何在不採用快速入門導覽課程中詳述的 Google 地圖範本的情況下,將 Android Studio 專案設為使用 Maps SDK for Android。
Google 地圖範本會自動設定基本地圖,並將其加進新的 Android Studio 專案,但您也可以將地圖新增至使用其他 Android Studio 範本的 Android 專案。如要這麼做,您需要手動設定專案,然後新增地圖。
步驟 1:設定 Android Studio
- 必須使用 Android Studio Arctic Fox 或更新版本。如果您尚未下載並安裝,請先完成此步驟。
- 確認您在 Android Studio 中使用的是 Android Gradle 外掛程式 7.0 以上版本。
步驟 2:設定 SDK
您可透過 Google 的 Maven 存放區存取 Maps SDK for Android 程式庫。如要將 SDK 加入應用程式,請按照下列步驟操作:
- 在頂層
settings.gradle
檔案的pluginManagement
區塊下方,加入 Gradle 外掛程式入口網站、Google Maven 存放區,以及 Maven 中央存放區。pluginManagement
區塊必須放在指令碼中的任何其他陳述式之前。pluginManagement { repositories { gradlePluginPortal() google() mavenCentral() } }
- 在頂層
settings.gradle
檔案的dependencyResolutionManagement
區塊下方,加入 Google Maven 存放區和 Maven 中央存放區:dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() } }
- 在模組層級
build.gradle
檔案中,加入 Maps SDK for Android 的 Google Play 服務依附元件。dependencies { // Maps SDK for Android implementation 'com.google.android.gms:play-services-maps:18.2.0' }
- 在模組層級
build.gradle
檔案中,將compileSdk
和minSdk
設為下列值:android { compileSdk 31 defaultConfig { minSdk 19 // ... }
步驟 3:將 API 金鑰加進專案
本節將說明如何儲存 API 金鑰,讓應用程式以安全的方式參照金鑰。API 金鑰不應該登錄在版本管控系統中;我們建議將金鑰儲存在位於專案根目錄的 secrets.properties
檔案內。如要進一步瞭解 secrets.properties
檔案,請參閱這篇文章中關於 Gradle 屬性檔案的說明。
建議您使用 Secrets Gradle Plugin for Android 來簡化這項工作。
如要在 Google 地圖專案中安裝 Secrets Gradle Plugin for Android,請按照下列步驟操作:
-
在 Android Studio 中開啟專案層級的
build.gradle
檔案,然後將下列程式碼加進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") } }
-
Open your module-level
build.gradle
file and add the following code to theplugins
element.Groovy
plugins { // ... id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' }
Kotlin
plugins { id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin") }
- Save the file and sync your project with Gradle.
-
Open the
secrets.properties
in your project level directory, and then add the following code. ReplaceYOUR_API_KEY
with your API key.MAPS_API_KEY=YOUR_API_KEY