Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

百度地圖定位 SDK(v3.1)實戰(三):把「我的位置」標在地圖上

編輯:Android 開發實例

本文的實作目標:透過 GPS 或 3G/2G 行動網路(基站)定位,把定位結果標注在地圖上;當使用者點擊地圖上代表「我的當前位置」的圖示時,顯示所在位置的詳細資訊。

so 與 jar 檔的導入、AndroidManifest.xml 的相關配置,前面兩篇已經交代過,這裡不再重複。

要注意:因為要用到百度提供的定位服務,AndroidManifest.xml 中一定要註冊對應的 Service,否則程式不會報錯,但也完全沒有任何效果——這是新手最容易卡住的一點。

一、設定定位參數並註冊結果接收器

mLocationClient = new LocationClient(this.getApplicationContext());
mLocationListener = new MyLocationListener();
mLocationClient.registerLocationListener(mLocationListener);

LocationClientOption locationOption = new LocationClientOption();
locationOption.setOpenGps(true);
locationOption.setCoorType("bd09ll");
locationOption.setPriority(LocationClientOption.GpsFirst);
locationOption.setAddrType("all");
locationOption.setProdName("通過GPS定位");
mLocationClient.setLocOption(locationOption);

Log.i(TAG, "BaiduMapMyLocationActivity 開啟定位");
mLocationClient.start();

二、把定位結果標注在地圖上

1. 自訂 BDLocationListener 處理定位結果

class MyLocationListener implements BDLocationListener {

    @Override
    public void onReceiveLocation(BDLocation location) {
        if (location == null) {
            return;
        }

        Log.i(TAG, "BaiduMapMyLocationActivity onReceiveLocation()");

        testLog(location);        // 方便測試查看
        markLocation(location);   // 在地圖上標注我當前的位置

        mBDLocation = location;
    }

    @Override
    public void onReceivePoi(BDLocation arg0) {
    }
}

2. 建立負責顯示當前位置的 Overlay 並設定資料

mLocationOverlay = new LocationOverlay(mMapView);
// 百度官方 API 文件說這是「打開指南針」,但實測預設就是開啟的
// mLocationOverlay.enableCompass();
locData = new LocationData();
mLocationOverlay.setData(locData);

3. 把 Overlay 加入覆蓋物清單並刷新地圖

mMapView.getOverlays().add(mLocationOverlay);
mMapView.refresh();

4. 把當前位置移到地圖中心

mMapController.animateTo(new GeoPoint(
        (int) (locData.latitude * 1e6),
        (int) (locData.longitude * 1e6)));

三、點擊「我的位置」顯示詳細資訊

自訂類別繼承 MyLocationOverlay,覆寫 protected boolean dispatchTap(),在方法體裡加入處理邏輯。

class LocationOverlay extends MyLocationOverlay {

    public LocationOverlay(MapView mapView) {
        super(mapView);
    }

    // 處理在「我的位置」座標上的點擊事件
    @Override
    protected boolean dispatchTap() {
        Log.i(TAG, "BaiduMapMyLocationActivity 處理在「我的位置」座標上的點擊事件 dispatchTap()");

        if (mBDLocation != null) {
            showLocation(mBDLocation);
        }

        return super.dispatchTap();
    }
}

四、實測中發現的問題

1. 最新 API 與官方文件有出入

  • mLocationOverlay.enableCompass():文件說是「打開指南針」,但實測預設就已經是開啟狀態。
  • BMapManager:文件寫了 start()(開啟百度地圖 API)與 stop()(終止 API,呼叫後不再回調),但新版 SDK 的 BMapManager 物件實際上已經沒有這兩個方法。

2. 呼叫 mLocationClient.start() 會導致 BaiduMapApplication.onCreate() 被再次執行

目前還沒觀察到功能受影響,但個人認為:既然先前已經初始化過地圖引擎,就不該再初始化一次,這是資源的浪費。官方提供的 demo 也有同樣情形,值得留意。

五、完整程式碼

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.easi.baidu.map"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:name=".BaiduMapApplication" >
        <activity
            android:configChanges="keyboardHidden|orientation"
            android:label="@string/app_name"
            android:name=".BaiduMapMyLocationActivity"
            android:screenOrientation="sensor" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

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

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCES_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_GPS" />

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

    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="false"
        android:resizeable="true"
        android:smallScreens="true" />

</manifest>

初始化地圖引擎、存放共享資源的 Application

package com.easi.baidu.map;

import android.app.Application;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.MKEvent;

/**
 * 初始化地圖引擎物件,存放共享資源。
 * 需在 AndroidManifest.xml 的 application 標籤加上 name 屬性。
 */
public class BaiduMapApplication extends Application {

    /** 申請的百度地圖 API Key */
    private static final String BAIDU_MAP_KEY = "8BB7F0E5C9C77BD6B9B655DB928B74B6E2D838FD";

    private static final String TAG = "BaiduMapApplication";

    /* package */ BMapManager mMapManager;
    /* package */ Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "BaiduMapApplication onCreate()");

        mContext = getApplicationContext();
        mMapManager = new BMapManager(getApplicationContext());

        initMapManager();
    }

    /**
     * 初始化 BMapManager 物件
     */
    public void initMapManager() {
        boolean result = mMapManager.init(BAIDU_MAP_KEY, new MKGeneralListener() {

            @Override
            public void onGetNetworkState(int error) {
                if (error == MKEvent.ERROR_NETWORK_CONNECT) {
                    Toast.makeText(mContext, "您的網絡出錯啦!", Toast.LENGTH_LONG).show();
                } else if (error == MKEvent.ERROR_NETWORK_DATA) {
                    Toast.makeText(mContext, "輸入正確的檢索條件!", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onGetPermissionState(int error) {
                if (error == MKEvent.ERROR_PERMISSION_DENIED) {
                    // 授權 Key 錯誤
                    Toast.makeText(mContext, "您的授權Key出錯!", Toast.LENGTH_LONG).show();
                }
            }
        });

        if (!result) {
            Toast.makeText(mContext, "初始化地圖引擎失敗!", Toast.LENGTH_LONG).show();
        } else {
            Log.i(TAG, "地圖引擎初始化成功!");
        }
    }

    @Override
    public void onTerminate() {
        Log.i(TAG, "BaiduMapApplication onTerminate()");

        if (mMapManager != null) {
            mMapManager.destroy();
            mMapManager = null;
        }

        super.onTerminate();
    }
}

需要用到百度地圖的 Activity 基類

package com.easi.baidu.map;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;

/**
 * 需要用到百度地圖的 Activity 基類
 */
public abstract class BaiduMapBaseActivity extends Activity {

    /** Application 物件的引用 */
    protected BaiduMapApplication mApplication;

    /** 顯示地圖的 View 元件 */
    protected MapView mMapView;

    /** MapView 控制器物件的引用 */
    protected MapController mMapController;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mApplication = (BaiduMapApplication) this.getApplication();

        if (mApplication.mMapManager == null) {
            Log.e("BaiduMapApplication",
                    "BaiduMapBaseActivity mApplication.mMapManager is NULL!");

            mApplication.mMapManager = new BMapManager(mApplication.mContext);
            mApplication.initMapManager();
        }

        setContentView(getLayoutId());

        mMapView = (MapView) this.findViewById(getMapViewId());
        mMapController = mMapView.getController();
    }

    /** 取得代表版面檔的 ID */
    public abstract int getLayoutId();

    /** 取得代表 MapView 物件的元件 ID */
    public abstract int getMapViewId();

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

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

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

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mMapView.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
}

定位功能的具體實作類

package com.easi.baidu.map;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;

/**
 * 提供透過 GPS 或 3G/2G 網路(基站)定位,並將結果標注在地圖上。
 * 點擊地圖上代表「我的當前位置」的點時,顯示位置詳細資訊。
 *
 * 註:GPS 可用且已取得定位結果時,不再發起網路請求,直接回傳座標給使用者;
 *     若 GPS 不可用,才發起網路請求進行定位。
 */
public class BaiduMapMyLocationActivity extends BaiduMapBaseActivity {

    private static final String TAG = "BaiduMapMyLocationActivity";

    /** 定位 SDK 的核心類 */
    private LocationClient mLocationClient;

    /** 顯示定位結果詳細資訊的 View */
    private TextView tvLocationResult;

    /** 標注我的位置的覆蓋物 */
    private MyLocationOverlay mLocationOverlay;

    /** 我的位置資訊資料 */
    private LocationData locData;

    /** 定位結果處理器 */
    private MyLocationListener mLocationListener;

    /** 暫時快取我的當前位置資料 */
    private BDLocation mBDLocation;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "BaiduMapMyLocationActivity onCreate()");

        mMapController.setZoom(15);
        mMapController.enableClick(true);

        tvLocationResult = (TextView) this.findViewById(R.id.tv_location_result);

        mLocationClient = new LocationClient(this.getApplicationContext());
        mLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mLocationListener);

        LocationClientOption locationOption = new LocationClientOption();
        locationOption.setOpenGps(true);
        locationOption.setCoorType("bd09ll");
        locationOption.setPriority(LocationClientOption.GpsFirst);
        locationOption.setAddrType("all");
        locationOption.setProdName("通過GPS定位");
        mLocationClient.setLocOption(locationOption);

        Log.i(TAG, "BaiduMapMyLocationActivity 開啟定位");
        mLocationClient.start();

        // 重新定位
        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mLocationClient != null && mLocationClient.isStarted()) {
                    mLocationClient.requestLocation();
                }
            }
        });

        mLocationOverlay = new LocationOverlay(mMapView);
        locData = new LocationData();

        tvLocationResult.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                tvLocationResult.setVisibility(View.GONE);
            }
        });
    }

    class LocationOverlay extends MyLocationOverlay {

        public LocationOverlay(MapView mapView) {
            super(mapView);
        }

        // 處理在「我的位置」座標上的點擊事件
        @Override
        protected boolean dispatchTap() {
            Log.i(TAG, "BaiduMapMyLocationActivity 處理在「我的位置」座標上的點擊事件 dispatchTap()");

            if (mBDLocation != null) {
                showLocation(mBDLocation);
            }

            return super.dispatchTap();
        }
    }

    /**
     * 顯示我當前位置的詳細資訊
     */
    private void showLocation(BDLocation location) {
        StringBuffer sb = new StringBuffer(256);
        sb.append(" time : ").append(location.getTime());
        sb.append("\n error code : ").append(location.getLocType());
        sb.append("\n latitude : ").append(location.getLatitude());
        sb.append("\n lontitude : ").append(location.getLongitude());

        // 判斷是否有定位精度半徑
        if (location.hasRadius()) {
            // 定位精度半徑,單位是公尺
            float accuracy = location.getRadius();
            Log.i(TAG, "accuracy = " + accuracy);
            sb.append("\n radius : ").append(location.getRadius());
        }

        if (location.getLocType() == BDLocation.TypeGpsLocation) {
            if (location.hasSpeed()) {
                sb.append("\n speed : ").append(location.getSpeed());
            }
            if (location.hasSateNumber()) {
                sb.append("\n satellite : ").append(location.getSatelliteNumber());
            }
        } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
            // 只有使用網路定位時,才能取得目前位置的反地理編碼描述
            if (location.hasAddr()) {
                String address = location.getAddrStr();
                Log.i(TAG, "address = " + address);
                sb.append("\n addr : ").append(address);
            }
        }

        tvLocationResult.setVisibility(View.VISIBLE);
        tvLocationResult.setText(sb);
    }

    /**
     * 在地圖上標注定位得到我當前的位置
     */
    private void markLocation(BDLocation location) {
        locData.latitude = location.getLatitude();
        locData.longitude = location.getLongitude();
        locData.direction = location.getDerect();

        if (location.hasRadius()) {
            locData.accuracy = location.getRadius();
        }

        mLocationOverlay.setData(locData);
        mMapView.getOverlays().add(mLocationOverlay);
        mMapView.refresh();

        // 將我的當前位置移動到地圖的中心點
        mMapController.animateTo(new GeoPoint(
                (int) (locData.latitude * 1e6),
                (int) (locData.longitude * 1e6)));
    }

    class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                return;
            }

            Log.i(TAG, "BaiduMapMyLocationActivity onReceiveLocation()");

            testLog(location);        // 方便測試查看
            markLocation(location);   // 在地圖上標注我當前的位置

            mBDLocation = location;
        }

        @Override
        public void onReceivePoi(BDLocation arg0) {
        }
    }

    /**
     * 印出測試 LOG 資訊
     */
    private void testLog(BDLocation location) {
        String province = location.getProvince();  // 省份
        String city = location.getCity();          // 城市
        String district = location.getDistrict();  // 區縣

        Log.i(TAG, "province = " + province);
        Log.i(TAG, "city = " + city);
        Log.i(TAG, "district = " + district);

        int type = location.getLocType();
        Log.i(TAG, "當前定位採用的類型是:type = " + type);

        String coorType = location.getCoorType();
        Log.i(TAG, "座標系類型:coorType = " + coorType);

        float derect = location.getDerect();
        Log.i(TAG, "derect = " + derect);
    }

    @Override
    public int getLayoutId() {
        return R.layout.main;
    }

    @Override
    public int getMapViewId() {
        return R.id.bmapView;
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "BaiduMapMyLocationActivity onDestroy() start");

        mLocationClient.stop();
        mLocationClient.unRegisterLocationListener(mLocationListener);
        this.mApplication.onTerminate();

        super.onDestroy();

        Log.i(TAG, "BaiduMapMyLocationActivity onDestroy() end");
    }
}

六、互動細節

點擊地圖上的藍色指南針圖示會展開位置資訊面板;再點一次該面板即可將其隱藏;按「重新定位」按鈕則會重新取得目前位置。

補充:我在測試時使用的是 Wi-Fi 網路定位,所以地址資訊不為 null;若改用純 GPS 定位,getAddrStr() 通常不會有值,這與 SDK 的設計有關——反地理編碼只在網路定位模式下提供。

原文轉自:https://blog.csdn.net/android_ls/article/details/8586229

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