Google Maps Android API v2 を利用して地図を表示する - Android

Google Maps Android API v2 を利用して地図を表示します。

事前準備

Google Play services モジュールがインストールされていない場合はAndroid SDK Managerからインストールする必要があります。インストール手順はこちらの記事を参照してください。

ライブラリのインポート

最初に Google Maps Android API v2のライブラリをインポートします。
Eclipseを起動し[File]メニューの[Import...]メニューを選択します。


[Import]ダイアログが表示されます。


[Import]ダイアログの"Android"カテゴリのノード下にある"Existing Android Code Into Workspace"を選択します。選択後[Next>]ボタンを押します。


下図のダイアログに切り替わります。"Root Directory:"欄の右側にある"Browse..."ボタンを押します。


フォルダの参照ダイアログが開きますので、Google Play Servicesのライブラリのフォルダを参照します。ADTバンドル版のAndroid SDKをインストールした場合は
(Android SDKの配置フォルダ)\sdk\extras\google\google_play_services\libproject\google-play-services_lib
になります。
選択ができたら[OK]ボタンを押してダイアログを閉じます。


インポートするプロジェクトの一覧が表示されます。一覧に"google-play-services_lib"以外のプロジェクトが表示された場合(サンプルなど)は左側のチェックボックスのチェックを外してインポートされないようにします。他の項目はデフォルトのままです。設定ができた後[Finish]ボタンを押します。


正常にインポートできると"Package Explorer"内に"google-play-services_lib"が追加されます。

プロジェクトの作成

Android アプリケーションプロジェクトを作成します。
[New Android Application]ダイアログボックスが表示されますので、以下を設定します。
  • Application Name: "SimpleGoogleMap"
  • Project Name: "SimpleGoogleMap"
  • Package Name: "com.iPentec.simplegooglemap"
  • Minimum Required SDK: "API 11: Android 3.0 (Honeycomb)"
  • Target SDK: "API 17: Android 4.2 (Jelly Bean)"
  • Compile With: "API 17: Android 4.2 (Jelly Bean)"
  • Theme: "Holo Light with Dark Action Bar"

注意

Google Maps Android API v2は Android 3.0以上でしか動作しません。Minimum Required SDKを"API 11: Android 3.0 (Honeycomb)"以上に設定する必要があります。

ライブラリの参照

先ほど作成したプロジェクトから先にインポートした"google-play-services_lib"ライブラリを参照できるように設定します。

"Package Explorer"から作成したプロジェクトのノードを選択し右クリックでポップアップメニューを表示します。メニューの[Properties]を選択します。


プロジェクトのプロパティダイアログが表示されます。左側のツリービューから[Android]を選択します。下図の画面が表示されます。ダイアログ下部の[Library]セクションの[Add]ボタンを押します。


[Project Selection]ダイアログが表示されます。一覧に"google-play-services_lib"が表示されていますのでこれをクリックして選択します。選択後[OK]ボタンを押します。


プロジェクトのプロパティダイアログに戻ると[Library]エリアに"google-play-services_lib"の参照が追加されていることが確認できます。[OK]ボタンを押してプロジェクトのプロパティダイアログを閉じます。

コード

以下のコードを記述します。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.iPentec.simplegooglemap"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />
	
    <permission
        android:name="com.iPentec.simplegooglemap.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
	
    <uses-feature android:glEsVersion="0x00020000" android:required="true" />
	
    <uses-permission android:name="com.iPentec.simplegooglemap.permission.MAPS_RECEIVE"/>
	
    <uses-permission android:name="android.permission.INTERNET"/>
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
	<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.iPentec.simplegooglemap.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="(Google Maps Android API v2のAPIキー)"/>
    </application>
</manifest>

解説

manifestタグ内の下記が追加部分です。
    <permission
        android:name="com.iPentec.simplegooglemap.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
	
    <uses-feature android:glEsVersion="0x00020000" android:required="true" />
	
    <uses-permission android:name="com.iPentec.simplegooglemap.permission.MAPS_RECEIVE"/>
	
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

applicationタグ内の下記が追加部分です。(Google Maps Android API v2のAPIキー)の部分にはAPIキーを入力します。APIキーの取得手順はこちらの記事を参照してください。
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="(Google Maps Android API v2のAPIキー)"/>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />
</RelativeLayout>

解説

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />
を追記します。上記のコードがGoogleMapが表示されるコントロールになります。

MainActivity.java

package com.iPentec.simplegooglemap;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends Activity {
  static final LatLng TOKYO_STATION = new LatLng(35.681588,139.76608); //東京駅の緯度経度
  static final LatLng SKY_TREE = new LatLng(35.709958,139.81083); //スカイツリーの緯度経度
  private GoogleMap map;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //ここから追加
    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    
    if (map!=null){
      MarkerOptions mo1 = new MarkerOptions();
      mo1.position(TOKYO_STATION);
      mo1.title("東京駅");
      Marker tokyost = map.addMarker(mo1);

      MarkerOptions mo2 = new MarkerOptions();
      mo2.position(SKY_TREE);
      mo2.title("スカイツリー");
      mo2.snippet("高いよ~");
      mo2.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
      Marker skytree = map.addMarker(mo2);

      map.moveCamera(CameraUpdateFactory.newLatLngZoom(TOKYO_STATION, 15));
      map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); 
    }
    //ここまで
   }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }
}

解説

クラス変数に以下を追加します。
  static final LatLng TOKYO_STATION = new LatLng(35.681588,139.76608); //東京駅の緯度経度
  static final LatLng SKY_TREE = new LatLng(35.709958,139.81083); //スカイツリーの緯度経度
  private GoogleMap map;

importに以下を追加します。
パッケージ名の解決ができずビルドエラーになる場合はライブラリの参照ができていないことが原因の可能性が高いです。先の手順に従ってプロジェクトのプロパティを設定してライブラリの参照を追加してください。
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

onCreate内の下記のコードが追加になります。
    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    
    if (map!=null){
      MarkerOptions mo1 = new MarkerOptions();
      mo1.position(TOKYO_STATION);
      mo1.title("東京駅");
      Marker tokyost = map.addMarker(mo1);

      MarkerOptions mo2 = new MarkerOptions();
      mo2.position(SKY_TREE);
      mo2.title("スカイツリー");
      mo2.snippet("高いよ~");
      mo2.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
      Marker skytree = map.addMarker(mo2);

      map.moveCamera(CameraUpdateFactory.newLatLngZoom(TOKYO_STATION, 15));
      map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); 
    }
Mapオブジェクトの取得
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
上記はリソースIDからMapオブジェクトを取得するコードです。

オブジェクトが有効かの判定
if (map!=null){
  ...
}
上記のif文内はMapオブジェクトが有効であった場合にのみ処理をします。

地図へのマーカーの追加
  MarkerOptions mo1 = new MarkerOptions();
  mo1.position(TOKYO_STATION);
  mo1.title("東京駅");
  Marker tokyost = map.addMarker(mo1);
上記コードがMapオブジェクトにマーカーを追加するコードです。マーカーの追加はMapオブジェクトのaddMarker()メソッドを呼び出すことで追加できます。引数にはマーカーの情報を与えるMarkerOptionsオブジェクトを与えます。MarkerOptionsオブジェクトのpositionメソッドでマーカーの設置座標を設定します。また、titleメソッドでマーカーのタイトルを設定します。

  MarkerOptions mo2 = new MarkerOptions();
  mo2.position(SKY_TREE);
  mo2.title("スカイツリー");
  mo2.snippet("高いよ~");
  mo2.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
  Marker skytree = map.addMarker(mo2);

同様のコードでもう一つマーカーを追加します。icon()メソッドでマーカーのアイコンを指定します。また、snippet()メソッドでスニペットを追加します。

実行結果

プロジェクトを実行します。APIキーなどの設定が正しくされていれば、下図の画面が表示されます。


拡大もできます。建物内は階表示もできます。ピンをタップするとタイトルに設定した"東京駅"が吹き出しで表示されます。


こちらはスカイツリーの場所に設置したマーカーです。建物内の階表示ができます。アイコンをタップするとタイトルに設定した文字とスニペットに設定した文字列が吹き出し内に表示されます。


地図を回転させることもできます。


このほか3D表示にも対応しています。

参考ページ

http://www.vogella.com/articles/AndroidGoogleMaps/article.html
著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-04
作成日: 2013-03-22
iPentec all rights reserverd.