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

百度地圖進階玩法:結合方向傳感器,讓地圖跟著你轉

編輯:關於 Android 程式設計

這一篇要替地圖補上兩件事:一是定位,二是結合方向傳感器,讓地圖能依手機的實際朝向確認方位。有了這兩項,地圖才真正開始「為我所用」。

動手要改的三個地方

整體改動其實集中在三個檔案:

a. 在 MainActivity 中加入定位程式碼,並實作定位監聽器 MyLocationListener;
b. 另外封裝一個方向傳感器類別 MyOrientationListener;
c. 別忘了在 AndroidManifest.xml 裡註冊百度定位所需的 Service。

不得不說,一開始照著思路讀下來差點暈頭——原作者寫得很清楚,但對新手而言資訊密度太高。整理了好一陣子才發現,有些程式碼在這個階段其實還沒真正用到,先放著也不影響運行。

那些差點讓我卡住的細節

最坑的一段是這行 import:

import com.baidu.mapapi.map.MyLocationConfigeration;

看起來沒問題吧?但就是報錯。一開始我以為是百度 SDK 的包沒導入正確,反覆檢查 demo 的 jar,上網各種搜尋 cannot resolve 的解法……折騰一小時後才發現,真正的兇手是拼字:MyLocationConfiguration。一個字母一個字母比對下去,才把這個坑填平。 SDK 裡確實存在拼錯的方法名 setMyLocationConfigeration,但類別名稱本身並沒拼錯,兩者混用就會爆炸。

另外提醒:定位相關功能一定要用真機測試,模擬器拿不到可靠的座標與傳感器資料。

本文完成的成果包含普通地圖、衛星地圖與即時交通三種顯示模式:

版面與素材:

布局檔:activity_main.xml

以 MapView 為底層,上層疊一塊可隱藏的資訊卡(店家名稱、距離、按讚數),做出類似 LBS 應用的樣子。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

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

        <RelativeLayout
            android:id="@+id/id_marker_info"
            android:layout_width="fill_parent"
            android:layout_height="220dp"
            android:layout_alignParentBottom="true"
            android:background="#CC4e5a6b"
            android:clickable="true"
            android:visibility="gone">

            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="150dp"
                android:layout_margin="10dp"
                android:background="@drawable/map_image_border_white"
                android:scaleType="fitXY"
                android:src="@drawable/map_iv" />

            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="50dp"
                android:layout_alignBottom="@+id/map_iv"
                android:background="@drawable/bg_map_bottom">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_centerVertical="true"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="老米家泡饃小炒"
                        android:textColor="#FFF5EB" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="距離 200 米"
                        android:textColor="#FFF5EB" />
                </LinearLayout>
            </RelativeLayout>
        </RelativeLayout>
    </com.baidu.mapapi.map.MapView>
</RelativeLayout>

MainActivity:定位 + 傳感器的合流點

關鍵觀念是:LocationClient 負責經緯度,MyOrientationListener 負責方位角,兩邊的資料最後都要組裝成 MyLocationData 交給地圖。因此兩處回呼(定位回呼與方向變化回呼)裡的程式碼幾乎一樣,這也是為什麼只要有一邊更新,圖層上的箭頭就會跟著動。

public class MainActivity extends Activity {

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    public MyLocationListener mMyLocationListener;

    private LocationMode mCurrentMode = LocationMode.NORMAL;
    private volatile boolean isFristLocation = true;

    private double mCurrentLantitude;
    private double mCurrentLongitude;
    private float mCurrentAccracy;

    private MyOrientationListener myOrientationListener;
    private int mXDirection;                  // 方向傳感器的 X 軸值

    private String[] mStyles = {"地圖模式【正常】", "地圖模式【跟隨】", "地圖模式【羅盤】"};
    private int mCurrentStyle = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 注意:SDKInitializer 必須在 setContentView 之前呼叫
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);

        isFristLocation = true;
        mMapView = (MapView) findViewById(R.id.id_bmapView);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(15.0f));

        initMyLocation();          // 初始化定位
        initOritationListener();   // 初始化方向傳感器
    }

    /** 初始化方向傳感器 */
    private void initOritationListener() {
        myOrientationListener = new MyOrientationListener(getApplicationContext());
        myOrientationListener.setOnOrientationListener(new OnOrientationListener() {
            @Override
            public void onOrientationChanged(float x) {
                mXDirection = (int) x;
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(mCurrentAccracy)
                        .direction(mXDirection)     // 順時針 0-360
                        .latitude(mCurrentLantitude)
                        .longitude(mCurrentLongitude)
                        .build();
                mBaiduMap.setMyLocationData(locData);

                BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                        .fromResource(R.mipmap.navi_map_gps_locked);
                MyLocationConfiguration config =
                        new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker);
                mBaiduMap.setMyLocationConfigeration(config);
            }
        });
    }

    /** 初始化定位相關設定 */
    private void initMyLocation() {
        mLocationClient = new LocationClient(this);
        mMyLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mMyLocationListener);

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setCoorType("bd09ll");   // 座標型別
        option.setScanSpan(1000);       // 每 1000ms 掃描一次
        mLocationClient.setLocOption(option);
    }

    /** 定位回呼 */
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null || mMapView == null) return;

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    .direction(mXDirection)
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .build();
            mBaiduMap.setMyLocationData(locData);

            mCurrentAccracy = location.getRadius();
            mCurrentLantitude = location.getLatitude();
            mCurrentLongitude = location.getLongitude();

            BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                    .fromResource(R.mipmap.navi_map_gps_locked);
            MyLocationConfiguration config =
                    new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker);
            mBaiduMap.setMyLocationConfigeration(config);

            // 只有第一次定位才把地圖飛過去,之後避免畫面被反覆拉回
            if (isFristLocation) {
                isFristLocation = false;
                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(ll));
            }
        }
    }

    @Override
    protected void onStart() {
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
        }
        myOrientationListener.start();     // 别忘了開傳感器
        super.onStart();
    }

    @Override
    protected void onStop() {
        mBaiduMap.setMyLocationEnabled(false);
        mLocationClient.stop();
        myOrientationListener.stop();      // 也别忘記關
        super.onStop();
    }

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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();              // 交還生命週期給 MapView
        mMapView = null;
    }
}

選單部分,普通地圖、衛星地圖、即時交通與「回到我的位置」都是直接呼叫 mBaiduMap 的對應方法;地圖模式則是在 NORMAL/FOLLOWING/COMPASS 之間循環切換,每換一次就重建一次 MyLocationConfiguration。另外,為了讓 menu 項目能顯示圖示,這裡用反射強制打開了 setOptionalIconsVisible。

MyOrientationListener:把傳感器包乾淨

這個類別做的事很單純:註冊方向傳感器、接收角度變化、透過自訂介面把值丟出去。有兩個細節值得注意——一是用 lastX 做門檻過濾,只有變化超過 1 度才回呼,避免畫面被雜訊刷得團團轉;二是 stop() 裡記得反註冊,否則會漏電。

public class MyOrientationListener implements SensorEventListener {

    private Context context;
    private SensorManager sensorManager;
    private Sensor sensor;
    private float lastX;
    private OnOrientationListener onOrientationListener;

    public MyOrientationListener(Context context) {
        this.context = context;
    }

    public void start() {
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null) {
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        }
        if (sensor != null) {
            sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
        }
    }

    public void stop() {
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) { }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
            float x = event.values[SensorManager.DATA_X];
            if (Math.abs(x - lastX) > 1.0) {          // 門檻過濾
                onOrientationListener.onOrientationChanged(x);
            }
            lastX = x;
        }
    }

    public void setOnOrientationListener(OnOrientationListener l) {
        this.onOrientationListener = l;
    }

    public interface OnOrientationListener {
        void onOrientationChanged(float x);
    }
}

AndroidManifest.xml:權限與 Service 缺一不可

百度定位對權限的要求不少,除了網路與 GPS,還包含寫入外部儲存、讀取手機狀態、震動等。另外務必填好自己的 API_KEY,並註冊 com.baidu.location.f 這個 Service。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_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.VIBRATE" />

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

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

選單檔 main.xml 則放五個項目:普通地圖、衛星地圖、開啟即時交通、我的位置、地圖模式,全部設為 app:showAsAction="never";資訊卡的白邊框用一個 shape 加 stroke 與 padding 就足夠了。

照著貼上確實很快就能跑起來,但建議還是把「為什麼要這樣寫」想通:定位與傳感器為何要分成兩個監聽、方向值為何要灌進 MyLocationData、MapView 的生命週期為何要對外轉發。這幾個問題答得出來,這份程式碼才算真正屬於你。

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