Android Studio プロジェクトをセットアップする

Places SDK for Android を使用するようにアプリを設定する手順は次のとおりです。 できます。Places SDK for Android を使用するすべてのアプリで必須です。

ステップ 1: Android Studio をセットアップする

このドキュメントでは、Android Studio HedgehogAndroid Gradle プラグイン バージョン 8.2 を使用した開発環境について説明します。

ステップ 2: SDK をセットアップする

Places SDK for Android ライブラリは、 Google の Maven リポジトリ。アプリに SDK を追加するには、以下の手順を行います。

  1. 最上位レベルの settings.gradle ファイルで、pluginManagement ブロック以下に Gradle プラグイン ポータルGoogle Maven リポジトリMaven セントラル リポジトリを含めます。pluginManagement ブロックは、スクリプト内の他のステートメントよりも前に配置する必要があります。
    pluginManagement {
        repositories {
            gradlePluginPortal()
            google()
            mavenCentral()
        }
    } 
  2. 最上位レベルの settings.gradle ファイルで、dependencyResolutionManagement ブロック以下に Google の Maven リポジトリMaven セントラル リポジトリを含めます。
    dependencyResolutionManagement {
        repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
        repositories {
            google()
            mavenCentral()
        }
    } 
  3. dependencies セクション(モジュール レベルの build.gradle ファイル)に依存関係を追加して、 追加すると、

    Groovy

    dependencies {
        // If updating kotlin-bom version number above, also edit project-level build.gradle definition of $kotlin_version variable
        implementation(platform("org.jetbrains.kotlin:kotlin-bom:$kotlin_version"))
        implementation 'com.google.android.libraries.places:places:3.3.0'
    }

    Kotlin

    dependencies {
        implementation(platform("org.jetbrains.kotlin:kotlin-bom:$kotlin_version"))
        implementation("com.google.android.libraries.places:places:3.5.0")
    }
  4. モジュール レベルの build.gradle ファイルで、compileSdk を設定します。 minSdk を次の値に設定します。

    Groovy

    android {
        compileSdk 34
    
        defaultConfig {
            minSdk 21
            // ...
        }
    }

    Kotlin

    android {
        compileSdk = 34
    
        defaultConfig {
            minSdk = 21
            // ...
        }
    }
  5. モジュール レベルの build.gradle ファイルの buildFeatures セクションで、次のようにします。 後で定義するメタデータ値にアクセスするために使用する BuildConfig クラスを追加します。 手順は以下のとおりです。

    Groovy

    android {
      // ...
      buildFeatures {
        buildConfig true
        // ...
      }
    }

    Kotlin

    android {
      // ...
      buildFeatures {
        buildConfig = true
        // ...
      }
    }

ステップ 3: API キーをプロジェクトに追加する

このセクションでは、アプリで安全に参照されるように API キーを保存する方法を説明します。API キーは、バージョン管理システムにはチェックインせず、プロジェクトのルート ディレクトリにある secrets.properties ファイルに保存することをおすすめします。secrets.properties ファイルについて詳しくは、Gradle プロパティ ファイルをご覧ください。

このタスクを効率化するには、Android 用 Secrets Gradle プラグインの使用をおすすめします。

Android 用 Secrets Gradle プラグインを Google マップ プロジェクトにインストールする手順は以下のとおりです。

  1. Android Studio で最上位レベルの build.gradle または build.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 はバージョン管理システムにチェックインされないため、このファイルにキーを保存します。
    PLACES_API_KEY=YOUR_API_KEY
  6. ファイルを保存します。
  7. 最上位レベルのディレクトリ(secrets.properties ファイルと同じフォルダ)に local.defaults.properties ファイルを作成し、次のコードを追加します。

    PLACES_API_KEY=DEFAULT_API_KEY

    このファイルの目的は、secrets.properties ファイルがない場合に API キーのバックアップ場所を提供し、ビルドが失敗しないようにすることです。この状況は、secrets.properties を省略したバージョン管理システムからアプリのクローンを作成し、API キーを提供するために secrets.properties ファイルをまだローカルに作成していない場合に発生する可能性があります。

  8. ファイルを保存します。
  9. Android Studio でモジュール レベルの build.gradle を開きます。または、 build.gradle.kts ファイルを開いて、secrets プロパティを編集します。もし secrets プロパティが存在しない場合は、追加してください。

    プラグインのプロパティを編集して、propertiesFileNamesecrets.propertiesdefaultPropertiesFileName を次に設定: local.defaults.properties、その他のプロパティを設定します。

    Groovy

    secrets {
        // To add your Maps API key to this project:
        // 1. If the secrets.properties file does not exist, create it in the same folder as the local.properties file.
        // 2. Add this line, where YOUR_API_KEY is your API key:
        //        MAPS_API_KEY=YOUR_API_KEY
        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 {
        // To add your Maps API key to this project:
        // 1. If the secrets.properties file does not exist, create it in the same folder as the local.properties file.
        // 2. Add this line, where YOUR_API_KEY is your API key:
        //        MAPS_API_KEY=YOUR_API_KEY
        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.*"
    }
            

ステップ 4. Places API クライアントを初期化する

アクティビティまたはフラグメント内で Places SDK for Android を初期化します。最初に 使用する SDK のバージョンを決定するには、Places SDK for Android、 Places SDK for Android(新規)プロダクトバージョンの詳細については SDK のバージョンを選択するをご覧ください。

次の例は、両方のバージョンの SDK を初期化する方法を示しています。

Places SDK for Android(新規)

を呼び出すときに API キーを渡す Places.initializeWithNewPlacesApiEnabled():

Kotlin

    // Define a variable to hold the Places API key.
    val apiKey = BuildConfig.PLACES_API_KEY

    // Log an error if apiKey is not set.
    if (apiKey.isEmpty() || apiKey == "DEFAULT_API_KEY") {
        Log.e("Places test", "No api key")
        finish()
        return
    }

    // Initialize the SDK
    Places.initializeWithNewPlacesApiEnabled(applicationContext, apiKey)

    // Create a new PlacesClient instance
    val placesClient = Places.createClient(this)
    

Java

    // Define a variable to hold the Places API key.
    String apiKey = BuildConfig.PLACES_API_KEY;

    // Log an error if apiKey is not set.
    if (TextUtils.isEmpty(apiKey) || apiKey.equals("DEFAULT_API_KEY")) {
      Log.e("Places test", "No api key");
      finish();
      return;
    }

    // Initialize the SDK
    Places.initializeWithNewPlacesApiEnabled(getApplicationContext(), apiKey);

    // Create a new PlacesClient instance
    PlacesClient placesClient = Places.createClient(this);
    

Places SDK for Android

を呼び出すときに API キーを渡す Places.initialize():

Kotlin

    // Define a variable to hold the Places API key.
    val apiKey = BuildConfig.PLACES_API_KEY

    // Log an error if apiKey is not set.
    if (apiKey.isEmpty() || apiKey == "DEFAULT_API_KEY") {
        Log.e("Places test", "No api key")
        finish()
        return
    }

    // Initialize the SDK
    Places.initialize(applicationContext, apiKey)

    // Create a new PlacesClient instance
    val placesClient = Places.createClient(this)
    

Java

    // Define a variable to hold the Places API key.
    String apiKey = BuildConfig.PLACES_API_KEY;

    // Log an error if apiKey is not set.
    if (TextUtils.isEmpty(apiKey) || apiKey.equals("DEFAULT_API_KEY")) {
      Log.e("Places test", "No api key");
      finish();
      return;
    }

    // Initialize the SDK
    Places.initialize(getApplicationContext(), apiKey);

    // Create a new PlacesClient instance
    PlacesClient placesClient = Places.createClient(this);
    

これで、Places SDK for Android の使用を開始できるようになりました。

ステップ 5: Android デバイスをセットアップする

Places SDK for Android を使用するアプリを実行するには、アプリを Android デバイスまたは Android にデプロイする必要があります。 Android 5.0 以降をベースとするエミュレータ 説明します。

  • Android デバイスを使用する場合は、ハードウェア デバイス上でのアプリの実行の手順を踏んでください。
  • Android Emulator を使用する場合は、Android Studio に付属している Android Virtual Device(AVD)Manager を使用して仮想デバイスを作成し、エミュレータをインストールしてください。

次のステップ

プロジェクトの構成が完了したら、 サンプルアプリ