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

百度地圖 SDK v3.5.0 定位功能詳解:從 LatLng 到定位圖層配置

編輯:關於 Android 程式設計

坐標——LatLng

定位開發中最高頻的概念就是坐標(經緯度),先把基本數據結構弄清楚。

LatLng 是地理坐標的基本結構,構造方法為 LatLng(double latitude, double longitude),兩個字段 latitude(緯度)與 longitude(經度)均為 public final double。

提醒:經緯度順序極易寫反,操作坐標時務必再三確認,且類型必須是 double。

坐標拾取系統

想快速拿到某個地點的坐標,或者準備幾個測試坐標,百度提供的坐標拾取系統最合適:在地圖上點擊任意位置,右上角方框中即會顯示該點坐標。

地理范圍——LatLngBounds

LatLngBounds 由西南與東北兩個角點確定一個矩形區域,字段為 southwest 與 northeast。它的常用方法有 contains(LatLng point) 判斷某坐標是否落在範圍內,以及 getCenter() 取得區域中心坐標。

其內部提供嵌套類 LatLngBounds.Builder,通過 include(LatLng point) 逐個納入坐標,最後調用 build() 生成對象。一般來說,凡是提供了 XXX.Builder 的類都建議優先使用 Builder,而非直接 new。

mBDMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
    @Override
    public void onMapLoaded() {
        LatLng northeast = new LatLng(31.192286, 121.445541);
        LatLng southwest = new LatLng(31.189922, 121.441624);
        LatLngBounds bounds = new LatLngBounds.Builder()
                .include(northeast).include(southwest).build();

        boolean isHas = bounds.contains(new LatLng(31.190795, 121.443564));
        Log.v("map", "是否包含:" + isHas
                + ",東北:" + bounds.northeast + " 西南:" + bounds.southwest);
    }
});

動手做一個簡單定位

布局文件 activity_location.xml 中放置 MapView 與切換定位圖標的單選按鈕組:

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

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

    <Button
        android:id="@+id/location_btn"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_alignParentRight="true"
        android:layout_below="@id/location_btn"
        android:orientation="vertical"
        android:background="#9e9e9e"
        android:padding="2dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RadioGroup
            android:id="@+id/location_rg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <RadioButton
                android:id="@+id/location_rb_defaulticon"
                android:text="默認圖標"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <RadioButton
                android:id="@+id/location_rb_customicon"
                android:text="自定義圖標"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </RadioGroup>
    </LinearLayout>
</RelativeLayout>

先準備一個基類,在使用 SDK 任何組件之前完成初始化,且必須在 setContentView 之前調用:

public class BaseActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 傳入 ApplicationContext,且需早於 setContentView
        SDKInitializer.initialize(getApplicationContext());
    }
}

定位主邏輯:

public class LocationDemo extends BaseActivity
        implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, BDLocationListener {

    private MapView mMapView;
    private BaiduMap mBDMap;
    private Button requestLocBtn;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private BitmapDescriptor mCurrentMarker;
    private RadioGroup rg;
    private LocationClient mLocClient;
    private boolean isFirstLoc = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        initView();
    }

    private void initView() {
        requestLocBtn = (Button) findViewById(R.id.location_btn);
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        requestLocBtn.setText("普通");
        requestLocBtn.setOnClickListener(this);

        rg = (RadioGroup) findViewById(R.id.location_rg);
        rg.setOnCheckedChangeListener(this);

        mMapView = (MapView) findViewById(R.id.location_bdmap);
        mBDMap = mMapView.getMap();
        mBDMap.setMyLocationEnabled(true); // 開啟定位圖層

        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(this);

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);          // 打開 GPS
        option.setCoorType("bd09ll");     // 坐標類型
        option.setScanSpan(1000);         // 定位間隔(毫秒)
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /** 循環切換普通態 → 跟隨態 → 羅盤態 */
    @Override
    public void onClick(View v) {
        switch (mCurrentMode) {
            case NORMAL:
                requestLocBtn.setText("跟隨");
                mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;
                break;
            case COMPASS:
                requestLocBtn.setText("普通");
                mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
                break;
            case FOLLOWING:
                requestLocBtn.setText("羅盤");
                mCurrentMode = MyLocationConfiguration.LocationMode.COMPASS;
                break;
        }
        mBDMap.setMyLocationConfigeration(
                new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
        mLocClient.start();
    }

    /** 切換定位圖標,傳 null 恢復默認 */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.location_rb_defaulticon:
                mCurrentMarker = null;
                break;
            case R.id.location_rb_customicon:
                mCurrentMarker = BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher);
                break;
        }
        mBDMap.setMyLocationConfigeration(
                new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation == null || mMapView == null) return;

        MyLocationData data = new MyLocationData.Builder()
                .accuracy(bdLocation.getRadius()) // 精度(半徑)
                .direction(100)                   // 方向角,順時針 0-360
                .latitude(bdLocation.getLatitude())
                .longitude(bdLocation.getLongitude())
                .build();
        mBDMap.setMyLocationData(data);

        if (isFirstLoc) {
            isFirstLoc = false;
            LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
            mBDMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(ll));
        }
    }

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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocClient.stop();               // 停止定位
        mBDMap.setMyLocationEnabled(false); // 關閉定位圖層
        mMapView.onDestroy();
        mMapView = null;                 // 釋放引用
    }
}

運行效果如下。

定位圖層配置——MyLocationConfiguration

構造方法為 MyLocationConfiguration(LocationMode mode, boolean enableDirection, BitmapDescriptor customMarker):mode 決定圖層顯示方式,默認 NORMAL;enableDirection 控制是否顯示方向信息;customMarker 為自定義定位圖標,可傳 null。

其中 LocationMode 是三個枚舉常量:

· NORMAL:普通態,更新定位數據時不對地圖做任何操作
· FOLLOWING:跟隨態,保持定位圖標位於地圖中心
· COMPASS:羅盤態,顯示方向圓圈並保持圖標居中

定位數據——MyLocationData

通過 MyLocationData.Builder 逐項設置:latitude / longitude 為經緯度,accuracy 為精度(米),direction 為 GPS 方向角,speed 為速度,satellitesNum 為衛星數目,最後 build() 生成對象並交給 setMyLocationData。

銷毀時的注意事項

onDestroy 中的代碼順序不能隨意調整:先 mLocClient.stop() 停止定位,再 setMyLocationEnabled(false) 關閉圖層,然後 mMapView.onDestroy(),最後把 mMapView 置為 null。

置空這一步涉及 Java 的內存回收機制:當 stu = null 之後,new Student() 產生的實例不再被任何引用指向,它就成為堆中的垃圾對象。虛擬機不會立刻回收,但最終一定會回收。

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