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

Android 百度地圖 SDK 整合步驟與權限設定

編輯:關於 Android 程式設計

在 Android 中整合百度地圖 SDK,通常需要下載 JAR 與 SO 檔、加入權限、配置 MapView,並在 Activity 中初始化地圖物件。若缺少函式庫或權限,常會導致地圖無法啟動。

下載與放置函式庫

先從百度地圖開發平台下載 SDK,通常會包含 JAR 檔與 SO 檔。將 JAR 放入專案的 libs 目錄,並把 SO 檔放入 libs/armeabi 或對應的 ABI 目錄。

接著在 Eclipse 或 Android Studio 中,將 JAR 加入 Java Build Path 或相依性設定。

加入權限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

版面配置

在 layout 中加入 MapView:

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

初始化地圖

mapManager = new BMapManager(getApplication());
mapManager.init("YOUR_API_KEY", null);
super.initMapActivity(mapManager);

mapView = (MapView) findViewById(R.id.map_View);
mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);

GeoPoint point = new GeoPoint((int) (47.118440 * 1E6), (int) (87.493147 * 1E6));
mapController = mapView.getController();
mapController.setCenter(point);
mapController.setZoom(12);

其中 API key 需要向百度地圖平台申請,並替換程式中的 YOUR_API_KEY。

生命週期管理

地圖物件通常需要在 onPause 中停止,在 onResume 中啟動,並在 onDestroy 中釋放:

protected void onPause() {
    if (mapManager != null) {
        mapManager.stop();
    }
    super.onPause();
}

protected void onResume() {
    if (mapManager != null) {
        mapManager.start();
    }
    super.onResume();
}

protected void onDestroy() {
    if (mapManager != null) {
        mapManager.destroy();
        mapManager = null;
    }
    super.onDestroy();
}

完成這些步驟後,即可顯示地圖、交通圖層與縮放控制。

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