一、定位功能的實現:
- 創建LocationClient
- implements BDLocationListener接口,重寫onReceive方法
- 創建並註冊listener
- 創建並設置LocationClientOption
LocationClientOption sample:
option.setCoorType("bd09ll");
option.setIsNeedAddress(true);
option.setOpenGps(true);
option.setScanSpan(1000);
onReceive sample:
Log.e("mybaidu","latitude:" + location.getLatitude() + "; longtitude:" + location.getLongitude());
MyLocationData data = new MyLocationData.Builder()//
.accuracy(location.getRadius())//
.latitude(location.getLatitude())//
.longitude(location.getLongitude())//
.build();
mBaiduMap.setMyLocationData(data);
if(isFirstIn){
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MapStatusUpdate msu = MapStatusUpdateFactory.newLatLngZoom(latLng,18);
mBaiduMap.animateMapStatus(msu);
isFirstIn = false;
Toast.makeText(getContext(), location.getAddrStr(),Toast.LENGTH_SHORT).show();
}
二、NOTE:
- 在
AndroidManifest.xml
中添加服務(百度API文檔中未提)
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote">
<intent-filter>
<action android:name="com.baidu.location.service_v2.2">
</action>
</intent-filter>
</service>
- 在onResume()中進行開啓定位
mBaiduMap.setMyLocationEnabled(true);
mLocationClient.start();
- 在onStop()中關閉定位
mBaiduMap.setMyLocationEnabled(false);
mLocationClient.stop(); - 在onPause()/onDestroy()中分別進行mapView的onPause()/onDestroy()
三、遇到的問題
1.打開地圖顯示一片白/藍,不顯示地圖,原因是申請百度地圖AK時,數字簽名(SHA1)不正確
- 解決方案:
- 使用命令行進入.android路徑(c:\users\用戶名.android)
- 開發模式下輸入命令:
keytool -list -v -keystore debugstore
回車,輸入密碼,默認是android(輸入時屏幕不顯示,直接打完按回車,當時被這個坑了好一會),即可獲得SHA1。
2.百度定位獲取經緯度正確,但是在地圖上顯示不正確,有一兩公里的偏差,原因是忘了把option設置給mLocationClient,這個是粗心導致的,也浪費了自己好多時間。
- 解決方案:
- 重複多次定位,記得一定要設置option