マーカーが配置された地図を追加する

このチュートリアルでは、Google マップを Android アプリに追加する方法を紹介します。地図には、特定の場所を示すマーカー(ピンとも呼ばれます)が配置されています。

Maps SDK for Android を使用して Android アプリを作成するには、このチュートリアルを参考にしてください。推奨される開発環境は Android Studio です。

コードを取得する

GitHub から、Google Maps Android API v2 サンプル リポジトリをダウンロードするかクローンを作成します。

アクティビティの Java バージョンを表示する:

    // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.example.mapwithmarker;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

/**
 * An activity that displays a Google map with a marker (pin) to indicate a particular location.
 */
public class MapsMarkerActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);

        // Get the SupportMapFragment and request notification when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map when it's available.
     * The API invokes this callback when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user receives a prompt to install
     * Play services inside the SupportMapFragment. The API invokes this method after the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        // Add a marker in Sydney, Australia,
        // and move the map's camera to the same location.
        LatLng sydney = new LatLng(-33.852, 151.211);
        googleMap.addMarker(new MarkerOptions()
            .position(sydney)
            .title("Marker in Sydney"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

    

アクティビティの Kotlin バージョンを表示する:

    // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.example.mapwithmarker

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions

/**
 * An activity that displays a Google map with a marker (pin) to indicate a particular location.
 */
class MapsMarkerActivity : AppCompatActivity(), OnMapReadyCallback {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps)

        // Get the SupportMapFragment and request notification when the map is ready to be used.
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
        mapFragment?.getMapAsync(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {
      val sydney = LatLng(-33.852, 151.211)
      googleMap.addMarker(
        MarkerOptions()
          .position(sydney)
          .title("Marker in Sydney")
      )
      googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}

    

開発プロジェクトを設定する

次のステップに沿って、Android Studio でチュートリアル プロジェクトを作成します。

  1. Android Studio をダウンロードしてインストールします。
  2. Android Studio に Google Play 開発者サービス パッケージを追加します。
  3. このチュートリアルの閲覧を開始した時点で行っていない場合は、Google Maps Android API v2 のサンプル リポジトリをダウンロードするかクローンを作成します。
  4. 次の手順でチュートリアル プロジェクトをインポートします。

    • Android Studio で、[File] > [New] > [Import Project] を選択します。
    • ダウンロードした Google Maps Android API v2 のサンプル リポジトリの保存先に移動します。
    • 次の場所で MapWithMarker プロジェクトを見つけます。
      PATH-TO-SAVED-REPO/android-samples/tutorials/java/MapWithMarker(Java)または
      PATH-TO-SAVED-REPO/android-samples/tutorials/kotlin/MapWithMarker(Kotlin)
    • プロジェクト ディレクトリを選択して、[Open] をクリックします。Android Studio が Gradle ビルドツールを使用してプロジェクトをビルドします。

必要な API を有効化して API キーを取得する

このチュートリアルを完了するには、必要な API が有効化された Google Cloud プロジェクトと、Maps SDK for Android の使用を許可されている API キーが必要です。詳しくは以下をご覧ください。

アプリに API キーを追加する

  1. プロジェクトの local.properties ファイルを開きます。
  2. 次の文字列を追加し、YOUR_API_KEY を実際の API キーの値に置き換えます。

    MAPS_API_KEY=YOUR_API_KEY
    

    アプリを作成すると、Android 用 Secrets Gradle プラグイン によって API キーがコピーされ、Android マニフェストでビルド バリアントとして使えるようになります(以下の説明をご覧ください)。

アプリをビルドして実行する

アプリをビルドして実行する手順:

  1. Android デバイスをコンピュータに接続します。手順に沿って、Android デバイスでデベロッパー オプションを有効にし、デバイスを検出するようにシステムを設定します。

    または、Android Virtual Device(AVD)Manager を使用して仮想デバイスを設定することもできます。エミュレータを指定する際は、Google API を含むイメージを選択する必要があります。詳しくは、Android Studio プロジェクトをセットアップするをご覧ください。

  2. Android Studio で [Run] メニュー オプション(またはプレイボタン アイコン)をクリックします。表示される指示に沿ってデバイスを選択します。

Android Studio で Gradle が起動してアプリが作成され、そのアプリがデバイスまたはエミュレータ上で実行されます。このページの画像のように、オーストラリア東海岸のシドニーを示すマーカーが立った地図が表示されます。

トラブルシューティング:

  • 地図が表示されない場合は、上記の手順どおりに API キーを取得してアプリに追加していることをご確認ください。Android Studio の Android Monitor のログでも、API キーに関するエラー メッセージを確認してください。
  • ログを表示してアプリをデバッグするには、Android Studio デバッグツールを使用します。

コードを理解する

このパートでは、MapWithMarker アプリの最も重要な部分について説明します。同様のアプリを作成する方法について理解を深めていただけます。

Android マニフェストを確認する

アプリの AndroidManifest.xml ファイルには次の要素が含まれています。

  • meta-data 要素を追加すると、アプリのコンパイルに使用された Google Play 開発者サービスのバージョンが埋め込まれます。

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    
  • API キーを指定する meta-data 要素を追加します。このチュートリアルのサンプルでは、API キーの値がビルド バリアント(先ほど定義したキーの名前に一致する)MAPS_API_KEY にマッピングされています。 アプリを作成すると、Android 用 Secrets Gradle プラグインによって、local.properties ファイル内のキーがマニフェスト ビルド バリアントとして使える状態になります。

    <meta-data
      android:name="com.google.android.geo.API_KEY"
      android:value="${MAPS_API_KEY}" />
    

    build.gradle ファイルで、次の行を使って API キーを Android マニフェストに渡します。

      id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    

マニフェストの詳細な例を以下に示します。

<?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright 2020 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mapwithmarker">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <!--
             The API key for Google Maps-based APIs.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="${MAPS_API_KEY}" />

        <activity
            android:name=".MapsMarkerActivity"
            android:label="@string/title_activity_maps"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

地図を追加する

Maps SDK for Android を使用して地図を表示します。

  1. アクティビティのレイアウト ファイル(activity_maps.xml)に <fragment> 要素を追加します。この要素では、地図のコンテナとして機能し、GoogleMap オブジェクトへのアクセス権を付与するよう SupportMapFragment を定義します。このチュートリアルでは、Android フレームワークの以前のバージョンとの下位互換性を確保するため、地図フラグメントの Android サポート ライブラリ バージョンを使用します。

    <!--
     Copyright 2020 Google LLC
    
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
    
          http://www.apache.org/licenses/LICENSE-2.0
    
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
    -->
    
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.mapwithmarker.MapsMarkerActivity" />
    
    
  2. アクティビティの onCreate() メソッドで、レイアウト ファイルをコンテンツ ビューとして設定します。FragmentManager.findFragmentById() を呼び出して、地図フラグメントに対するハンドルを取得します。次に、getMapAsync() を使用して、地図コールバックを登録します。

    Java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);
    
        // Get the SupportMapFragment and request notification when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    

    Kotlin

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps)
    
        // Get the SupportMapFragment and request notification when the map is ready to be used.
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
        mapFragment?.getMapAsync(this)
    }
    
  3. OnMapReadyCallback インターフェースを実装し、GoogleMap オブジェクトが使用可能な場合に地図を設定するよう onMapReady() メソッドをオーバーライドします。

    Java

    public class MapsMarkerActivity extends AppCompatActivity
            implements OnMapReadyCallback {
    
        // ...
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            LatLng sydney = new LatLng(-33.852, 151.211);
            googleMap.addMarker(new MarkerOptions()
                .position(sydney)
                .title("Marker in Sydney"));
        }
    }
    

    Kotlin

    class MapsMarkerActivity : AppCompatActivity(), OnMapReadyCallback {
    
        // ...
    
        override fun onMapReady(googleMap: GoogleMap) {
          val sydney = LatLng(-33.852, 151.211)
          googleMap.addMarker(
            MarkerOptions()
              .position(sydney)
              .title("Marker in Sydney")
          )
        }
    }
    

デフォルトでは、ユーザーがマーカーをタップすると Maps SDK for Android で情報ウィンドウのコンテンツが表示されます。デフォルトの動作で問題なければ、マーカーにクリック リスナーを追加する必要はありません。

次のステップ

マップ オブジェクトと、マーカーを使ってできることについて、詳しく確認します。