AndroidManifest.xmlに設定を追加
MapViewではネットワーク、GPSを使用しますので以下の設定をmanifestに追加します。
<!-- MapViewを使用するのに必要な設定 --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" ></uses-permission> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
また、デフォルト設定だと画面が回転した時に毎回現在地を取りにいくので回転してもonCreateが読み込まれないように地図面のActivityにandroid:configChanges="orientation"を追加します。
<activity
android:label="@string/app_name"
android:configChanges="orientation"
android:name=".InnerSearchActivity" >
現在地周辺の地図を表示
アプリ起動時に今回独自で作成したLocationControlクラスを使用し、現在地の取得を行います。LocationControl::startLocation で位置情報の取得を開始します。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
~ 中略 ~
// 起動時に現在地を取得
if (m_locationControl == null) {
m_locationControl = new LocationControl(this, this);
m_locationControl.setTimer(2000);
m_locationControl.startLocation(false);
}
~ 中略 ~
}
結果をLocationControl::onCustomLocationChangedで受け取り、ここでLocationControlを停止させます。LocationControl::getLocationで位置情報を受け取り、そこから緯度経度を取得します。取得した緯度経度をGeoPoint形式にし、MapViewに渡すと現在地周辺の地図が表示されます。
取得に失敗した場合はLocationControl::onCustomLocationErrorに入り、アラートダイアログで失敗したことを知らせます。
@Override
public void onCustomLocationChanged(LocationControl location) {
// 位置情報を取得して変数にセット
m_loca = m_locationControl.getLocation();
stopGPS();
// 取得した位置情報から緯度経度を別々に取得する
firstLat = m_loca.getLatitude();
firstLon = m_loca.getLongitude();
int cLat = (int) (firstLat * 1000000);
int cLon = (int) (firstLon * 1000000);
startPos = new GeoPoint(cLat, cLon);
// 取得した位置に地図を移動させる
MapController mapctl = mapview.getMapController();
mapctl.animateTo(startPos);
}
@Override
public void onCustomLocationError(LocationControl locationControl) {
m_loca = m_locationControl.getLocation();
stopGPS();
// 位置情報取得失敗をアラートダイアログで表示
new AlertDialog.Builder(this).setTitle("位置情報を取得出来ませんでした。")
.setPositiveButton("OK", null).show();
}
