Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用百度地圖 SDK 打造自己的地圖 App

編輯:關於 Android 程式設計

本文以百度地圖 API 為基礎,說明如何從零開始做出一個具備定位、標識物、地圖模式切換與即時路況的簡單地圖應用。

一、版面配置

<com.baidu.mapapi.map.MapView
    android:id="@+id/bmapView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true" />

二、要定義的變數

private BaiduMap mBaiduMap;
private MapView mMapView;
private LocationClient mLocationClient;
private boolean isFirstIn = true;

三、初始化

mMapView = (MapView) findViewById(R.id.bmapView);
mBaiduMap = mMapView.getMap();

四、在使用 SDK 各元件之前先初始化 Context

// 傳入 ApplicationContext
// 注意:這個方法要在 setContentView 之前呼叫
SDKInitializer.initialize(getApplicationContext());

這一行是最常見的崩潰原因。順序寫錯會導致地圖畫面全黑或直接 NullPointerException。

五、把地圖的生命週期和 Activity 綁定

MapView 內部有 OpenGL 繪製執行緒與網路連線,必須跟著 Activity 一起呼吸,否則會洩漏或畫面凍結。

@Override
protected void onStart() {
    super.onStart();
    mBaiduMap.setMyLocationEnabled(true);
    if (!mLocationClient.isStarted()) {
        mLocationClient.start();
    }
}

@Override
protected void onResume() {
    super.onResume();
    // 在 Activity 執行 onResume 時呼叫 mMapView.onResume(),實現地圖生命週期管理
    mMapView.onResume();
}

@Override
protected void onPause() {
    super.onPause();
    // 在 Activity 執行 onPause 時呼叫 mMapView.onPause()
    mMapView.onPause();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mMapView.onDestroy();
}

六、用 Option 選單切換地圖模式

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0, 1, 0, "普通地圖");
    menu.add(0, 2, 0, "衛星地圖");
    menu.add(0, 3, 0, "實時交通(off)");
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case 1: // 普通地圖
            mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
            break;
        case 2: // 衛星地圖
            mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
            break;
        case 3: // 即時路況開關
            if (mBaiduMap.isTrafficEnabled()) {
                mBaiduMap.setTrafficEnabled(false);
                item.setTitle("實時交通(off)");
            } else {
                mBaiduMap.setTrafficEnabled(true);
                item.setTitle("實時交通(on)");
            }
            break;
    }
    return super.onOptionsItemSelected(item);
}

七、在地圖上添加標識物

// 定義 Maker 座標點
LatLng point = new LatLng(39.963175, 116.400244);

// 建構 Marker 圖示
BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher);

// 建構 MarkerOption,用於在地圖上添加 Marker
OverlayOptions option = new MarkerOptions()
        .position(point)
        .icon(bitmap);

// 在地圖上添加 Marker,並顯示
mBaiduMap.addOverlay(option);

八、GPS 定位的三個步驟

要用到的類:LocationClient 與 BDLocationListener。

(1)建立 LocationClient 並註冊監聽

MyLocationListener myLocationListener = new MyLocationListener();
mLocationClient = new LocationClient(getApplicationContext());
// 註冊監聽函數
mLocationClient.registerLocationListener(myLocationListener);

(2)用 LocationClientOption 設定定位屬性

LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationMode.Hight_Accuracy); // 高精度定位模式
option.setCoorType("bd09ll");   // 回傳百度經緯度,預設值為 gcj02
option.setScanSpan(1000);       // 定位請求間隔,單位毫秒
option.setIsNeedAddress(true);  // 回傳結果包含地址資訊
option.setNeedDeviceDirect(true); // 回傳結果包含手機機頭方向
mLocationClient.setLocOption(option);

這裡的 setCoorType("bd09ll") 值得特別注意:百度使用的是自己偏移過的 BD-09 座標系,而 Google 與 OSM 用的是 WGS-84。如果把百度回傳的座標直接丟給其他地圖服務,會有幾百公尺的偏移。

(3)監聽器的實作

private class MyLocationListener implements BDLocationListener {

    @Override
    public void onReceiveLocation(BDLocation location) {
        MyLocationData data = new MyLocationData.Builder()
                .accuracy(location.getRadius())
                .latitude(location.getLatitude())
                .longitude(location.getLongitude())
                .build();
        mBaiduMap.setMyLocationData(data);

        // 判斷第一次進入,定位到目前所在位置
        if (isFirstIn) {
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
            mBaiduMap.animateMapStatus(msu);
            Toast.makeText(getApplicationContext(), location.getAddrStr(), 3000).show();
            isFirstIn = false;
        }
    }
}

用 isFirstIn 這個旗標限制「只在第一次定位時移動地圖中心」,避免後續每次位置更新都把地圖拉回來,讓使用者無法自由平移——這是地圖 App 最基本的體驗要求。

九、需要加入的權限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!-- 這個權限用於進行網路定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

十、在 application 中宣告

<meta-data
    android:name="com.baidu.lbsapi.API_KEY"
    android:value="OSzBVaOV08hT2o7yNBIq4NFS" />

<service
    android:name="com.baidu.location.f"
    android:enabled="true"
    android:process=":remote" />

務必把上面那個 API_KEY 換成你自己申請的金鑰。它與「SHA1 + 套件名稱」綁定,直接抄範例裡的值在你的裝置上一定會失敗,通常表現為地圖空白並在 logcat 印出 current app has not been authorized。申請流程是在百度地圖開放平台建立應用、填入套件名稱與簽章 SHA1。

十一、Android 6.0 之後的執行期權限

定位權限屬於「危險權限」,光在 Manifest 宣告不夠,必須在執行期動態向使用者請求:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this,
            new String[]{ Manifest.permission.ACCESS_FINE_LOCATION }, 1);
}

並在 onRequestPermissionsResult() 中處理使用者允許或拒絕的結果,且只有在取得權限後才呼叫 mLocationClient.start()。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved