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

Flutter プロジェクトのセットアップに入る前に、始める前にに記載された事前準備を済ませてください。課金を有効化して API キーを作成すると、アプリの開発に使う Flutter プロジェクトをセットアップできるようになります。

ステップ 1: 必要なソフトウェアをインストールする

Google Maps for Flutter パッケージを使ってプロジェクトを作成するには、Flutter SDK をインストールして、ターゲット プラットフォーム用の開発環境をセットアップする必要があります。詳しくは Flutter のインストール ガイドをご覧ください。

ステップ 2: Google Maps for Flutter パッケージを新しいプロジェクトにインストールする

Fulutter では、Google Maps for Flutter パッケージをプラグインとして利用できます。

Flutter プロジェクトを作成し、Maps プラグインを追加します。

  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、ウェブです。現在のところ、ブラウザ以外のデスクトップ アプリケーションは Google Maps SDK でサポートされていません。
  2. 作成したプロジェクトに、Google Maps for Flutter パッケージのプラグインを追加します。
    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 の設定を行う際は、実際の固有アプリケーション ID を指定します。
  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 プロジェクトに追加します。Flutter の場合、この API キーをすべてのターゲット プラットフォーム(iOS、Android、ウェブ)に追加する必要があります。

以下の例で YOUR_API_KEY とある箇所は、実際の API キーに置き替えてください。

Android

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

    MAPS_API_KEY=DEFAULT_API_KEY

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

  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 キーのメタデータ名を 1 つのみ指定できます。両方を指定すると、API から例外がスローされます。

iOS

API キーを AppDelegate.swift ファイルに追加します。

  1. お好みの IDE で、Flutter プロジェクトの ios/Runner/AppDelegate.swift ファイルを開きます。
  2. アプリに Google Maps for Flutter パッケージを追加するため、次のインポート文を追加します。
  3. import GoogleMaps
  4. application(_:didFinishLaunchingWithOptions:) メソッドに API キーを追加します。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)
  }
}

ウェブ

API キーをアプリケーション ファイル index.html に追加します。

  1. お好みの IDE で、Flutter プロジェクトの web/index.html ファイルを開きます。
  2. 次のスクリプトタグを <head> タグ内に追加します。YOUR_API_KEY とある箇所は、実際の API キーに差し替えてください。
    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
        key: "YOUR_API_KEY",
        v: "weekly",
        // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
        // Add other bootstrap parameters as needed, using camel case.
      });
    </script>
    
  3. index.html ファイルを保存して閉じます。

    index.htmlhead セクション全体は、次のようになります。

        <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>
            (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
              key: "YOUR_API_KEY",
              v: "weekly",
              // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
              // Add other bootstrap parameters as needed, using camel case.
              });
          </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<MyApp> createState() => _MyAppState();
          }
          
          class _MyAppState extends State<MyApp> {
            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 を呼び出すたびに行います。開発システム内に、実行中のエミュレータも接続済みのテストデバイスも存在しない場合は、自動的に Chrome が起動されます。

    どのプラットフォームでも、オーストラリアのシドニーを中心とする地図が表示されるはずです。地図が表示されない場合は、対応するターゲット プロジェクトに適切な API キーを追加できているか確認してください。

次のステップ

これで API キーと Flutter プロジェクトが用意できたので、アプリを作成・実行する準備が整いました。 Google Maps for Flutter パッケージには、開発を始めるのに役立つチュートリアルやサンプルアプリが豊富に用意されています。詳しくは以下のリソースをご覧ください。