今回は、GPSの利用方法などについて書いていきます。
レイアウトを利用
レイアウトを利用するには、まずレイアウトに以下のものを追加します。
<fragment
android:id="@+id/my_map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
これがv2でのマップビューとなります。idはご自由に変更してください。
次に、FragmentActivityを継承しているアクティビティに対し、以下のように設定します。
public class Mapv2Test extends FragmentActivity{
/**
* GoogleMap
*/
private GoogleMap mMap;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
// mapクラス関連の初期化
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.my_map)).getMap();
}
}
これで自由にレイアウトができるようになりました。
各種機能の利用
// 拡大・縮小ボタンを表示
mMap.getUiSettings().setZoomControlsEnabled(true);
// 通常の地図に変更
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//コンパスの有効化
mMap.getUiSettings().setCompassEnabled(true);
//現在位置を獲得する
mMap.setMyLocationEnabled(true);
現在位置の獲得
//現在位置を獲得するようにする
mMap.setMyLocationEnabled(true);
//現在位置の獲得(パラメータ)
Location l = mMap.getMyLocation();
また、動的に座標を獲得したい場合は、今まで通りLocationManagerが使えます。
表示位置を保持
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
if (savedInstanceState == null) {
// First incarnation of this activity.
mapFragment.setRetainInstance(true);
} else {
// Reincarnated activity. The obtained map is the same map instance in the previous
// activity life cycle. There is no need to reinitialize it.
mMap = mapFragment.getMap();
}
setUpMapIfNeeded();
setUpMapIfNeeded()は以下の通りです。
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
}
}
前回起動した時の座標を覚えておきたい場合は、以下のようにします。
// mapクラス関連の初期化
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.my_map);
// 初期化
if (savedInstanceState == null) {
// 初期起動
mapFragment.setRetainInstance(true);
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
} else {
mMap = mapFragment.getMap();
}
画像を地図平面上にベタッと貼り付けたい場合は、GroundOverlayを使用します。
mGroundOverlay = mMap.addGroundOverlay(new GroundOverlayOptions()
.image(BitmapDescriptorFactory
.fromResource(R.drawable.イメージ)).position(
mMap.getMyLocation(), 5));
地図上から追加した画像を消したい場合は以下の通りです。
mGroundOverlay.remove();
とりあえず今回はここまでで。