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

百度地圖 API 實作筆記(四):定位 SDK 串接與地圖標記

編輯:關於 Android 程式設計

前言

百度地圖把「定位」和「基礎地圖」拆成兩套 SDK,各自有獨立的 jar 與 so 庫,配置方式也不完全相同。很多人第一次串接時栽在這裡:以為下載了地圖 SDK 就順便把定位搞定,結果怎麼跑都拿不到座標。所以動手前,先把定位 SDK 的官方說明讀一遍。

一、環境配置

下載對應版本的定位 SDK,把 jar 與 so 放進 libs 目錄。若使用 Android Studio,記得告訴它 so 在哪:

sourceSets {
    main {
        jniLibs.srcDirs = ['libs']
    }
}

接著在 application 標籤中聲明定位 Service。每個 App 擁有獨立的定位服務,這步不能省:

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

權限宣告

<!-- 網路定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- GPS 定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 讀取 WiFi 資訊,網路定位會用到 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 讀取網路狀態與電信商資訊 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_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.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

Android 6.0 以上要特別注意。M 版本引入了動態權限機制,就算你在 Manifest 裡寫滿了權限,不主動向使用者申請,執行期一樣拿不到。我在真機上實測時就卡了幾分鐘——如果定位一直失敗,先跳到系統設定把權限手動開給 App,確認是不是這個問題,再回頭查程式碼。

AK 配置沿用基礎地圖的做法即可,這裡不再重複。

二、佈局檔

一個輸入框顯示定位結果、一個按鈕觸發定位、下方放 MapView:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="mapdemo.example.com.selfbaidumap.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/et_locationresult"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="3" />

        <Button
            android:id="@+id/bt_locate"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="定位" />
    </LinearLayout>

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

三、程式碼實作

public class MainActivity extends AppCompatActivity {

    private MapView bmapView;
    private BitmapDescriptor bitmap = null;
    private BaiduMap mBaiduMap = null;
    private LocationClient mLocationClient = null;
    private BDLocationListener myListener = new MyLocationListener();
    private EditText editTextLocationResult;
    private Button doLocateButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);

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

        // Marker 點擊事件:彈出資訊窗
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.getExtraInfo() != null) {
                    Bundle bundle = marker.getExtraInfo();
                    LatLng latlng = bundle.getParcelable("LatLng");
                    String address = bundle.getString("ADDRESS");

                    TextView tv = new TextView(MainActivity.this);
                    tv.setBackgroundResource(R.drawable.marker_info_bg);
                    tv.setTextColor(Color.WHITE);
                    tv.setText(address);

                    InfoWindow info = new InfoWindow(tv, latlng, -47);
                    mBaiduMap.showInfoWindow(info);
                }
                return false;
            }
        });

        doLocateButton = (Button) findViewById(R.id.bt_locate);
        doLocateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocate();
            }
        });

        editTextLocationResult = (EditText) findViewById(R.id.et_locationresult);
        bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);

        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        initLocation();
    }
}

定位參數設定

這一段 options 看起來項目很多,但絕大多數都有合理預設值,實務上真正需要調整的其實只有幾個:

private void initLocation() {
    LocationClientOption option = new LocationClientOption();

    // 定位模式:高精度 / 低功耗 / 僅設備
    option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);

    // 回傳座標系,預設 gcj02
    option.setCoorType("bd09ll");

    // 定位間隔,單位 ms,官方建議不低於 1000
    int span = 1000;
    option.setScanSpan(span);

    option.setIsNeedAddress(true);          // 需要地址資訊
    option.setOpenGps(true);                // 允許使用 GPS
    option.setLocationNotify(true);         // GPS 有效時每秒輸出一次結果
    option.setIsNeedLocationDescribe(true); // 位置語意化描述,如「在北京天安門附近」
    option.setIsNeedLocationPoiList(true);  // 需要周邊 POI 清單
    option.setIgnoreKillProcess(false);     // stop 時是否終止定位進程
    option.SetIgnoreCacheException(false);  // 是否收集 crash 資訊
    option.setEnableSimulateGps(false);     // 是否過濾 GPS 模擬結果

    mLocationClient.setLocOption(option);
}

private void startLocate() {
    if (mLocationClient != null) {
        mLocationClient.start();
    }
}

生命週期:MapView 必須跟著走

MapView 不是丟著不管就行的控制項,它會自己也走一次生命週期。漏掉對應的呼叫,常見症狀是返回後地圖空白或渲染異常:

@Override
protected void onResume() {
    if (bmapView != null) bmapView.onResume();
    super.onResume();
}

@Override
protected void onPause() {
    if (bmapView != null) bmapView.onPause();
    super.onPause();
}

@Override
protected void onDestroy() {
    if (bmapView != null) bmapView.onDestroy();
    if (bitmap != null) bitmap.recycle();   // BitmapDescriptor 記得回收
    super.onDestroy();
}

位置回呼:分情況處理

public class MyLocationListener implements BDLocationListener {
    @Override
    public void onReceiveLocation(BDLocation location) {
        StringBuffer sb = new StringBuffer(256);
        sb.append("time : ").append(location.getTime());
        sb.append("\nerror code : ").append(location.getLocType());
        sb.append("\nlatitude : ").append(location.getLatitude());
        sb.append("\nlontitude : ").append(location.getLongitude());
        sb.append("\nradius : ").append(location.getRadius());

        if (location.getLocType() == BDLocation.TypeGpsLocation) {
            // GPS 定位結果,可額外取得速度、衛星數、海拔、方向
            sb.append("\nspeed : ").append(location.getSpeed());            // km/h
            sb.append("\nsatellite : ").append(location.getSatelliteNumber());
            sb.append("\nheight : ").append(location.getAltitude());        // m
            sb.append("\ndirection : ").append(location.getDirection());    // 度
            sb.append("\naddr : ").append(location.getAddrStr());
            sb.append("\ndescribe : ").append("gps定位成功");
        } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
            // 網路定位結果
            sb.append("\naddr : ").append(location.getAddrStr());
            sb.append("\noperationers : ").append(location.getOperators());
            sb.append("\ndescribe : ").append("網絡定位成功");
        } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
            sb.append("\ndescribe : ").append("離線定位成功,離線定位結果也是有效的");
        } else if (location.getLocType() == BDLocation.TypeServerError) {
            sb.append("\ndescribe : ").append("服務端定位失敗,可回報 IMEI 與定位時間給官方排查");
        } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
            sb.append("\ndescribe : ").append("網路不通導致定位失敗,請檢查連線");
        } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
            sb.append("\ndescribe : ").append("缺少有效定位依據,飛行模式下常見,可嘗試重啟");
        }

        sb.append("\nlocationdescribe : ").append(location.getLocationDescribe());

        List<Poi> list = location.getPoiList();
        if (list != null) {
            sb.append("\npoilist size = : ").append(list.size());
            for (Poi p : list) {
                sb.append("\npoi= : ").append(p.getId() + " " + p.getName() + " " + p.getRank());
            }
        }

        Log.i("BaiduLocationApiDem", sb.toString());
        editTextLocationResult.setText(location.getAddrStr());
        addMark(location.getLatitude(), location.getLongitude(), location.getAddrStr());
        mLocationClient.stop();
    }
}

上面這份回呼寫得比較囉嗦,是因為照搬了官方 Demo 以便對照各欄位。自己專案裡通常只取經緯度與地址就夠了。

在地圖上打標記

private void addMark(double latitude, double longitude, String address) {
    LatLng latlng = new LatLng(latitude, longitude);

    // 用 Bundle 攜帶資料,點擊 Marker 時再取出來
    Bundle bundle = new Bundle();
    bundle.putString("ADDRESS", address);
    bundle.putParcelable("LatLng", latlng);

    OverlayOptions option = new MarkerOptions()
            .icon(bitmap)
            .extraInfo(bundle)
            .position(latlng);

    if (mBaiduMap != null) {
        mBaiduMap.addOverlay(option);
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(latlng));
    }
}

實測結果

(圖中個人位置資訊已作處理,實際 Demo 會以你的真實位置為準。)

整趟走下來,最容易翻車的其實不是程式碼,而是那三份配置:so 路徑、Service 宣告、以及 6.0 以上的動態權限。這三項確認過,剩下的照官方 API 呼叫即可。

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