編輯:關於 Android 開發
本文示範如何在 Android Studio 中接入百度定位 SDK,實現地圖上的實時定位。開發環境為 Windows 7 64 位 + Android Studio。地圖顯示與工程配置部分可參考上一篇《配置工程、顯示地圖》。

最初自己逐行照著寫,定位始終不成功,也找不到原因,最後是對照百度官網的 Demo 才跑通。所以下面的程式碼骨架基本來自官方範例,這裡做了一些整理與註解。
public class BaiDuMapActivity extends Activity {
/** 定位 SDK 核心類 */
private LocationClient locationClient;
/** 定位監聽 */
public MyLocationListenner myListener = new MyLocationListenner();
/** 百度地圖控件 */
private MapView mapView;
/** 百度地圖對象 */
private BaiduMap baiduMap;
boolean isFirstLoc = true; // 是否首次定位
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_bai_du_map);
// 地圖初始化
mapView = (MapView) findViewById(R.id.bmapView);
baiduMap = mapView.getMap();
baiduMap.setMyLocationEnabled(true); // 開啟定位圖層
// 定位初始化
locationClient = new LocationClient(this);
locationClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 開啟 GPS
option.setCoorType("bd09ll"); // 設定座標類型
option.setScanSpan(1000); // 定位請求間隔(毫秒)
locationClient.setLocOption(option);
locationClient.start();
}
/** 定位 SDK 監聽函數 */
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
// map view 銷毀後不再處理新接收的位置
if (location == null || mapView == null) {
return;
}
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
.direction(100) // 方向角,順時針 0-360
.latitude(location.getLatitude())
.longitude(location.getLongitude())
.build();
baiduMap.setMyLocationData(locData);
if (isFirstLoc) {
isFirstLoc = false;
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
MapStatus.Builder builder = new MapStatus.Builder();
builder.target(ll).zoom(18.0f);
baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
}
}
public void onReceivePoi(BDLocation poiLocation) { }
}
@Override
protected void onPause() {
mapView.onPause();
super.onPause();
}
@Override
protected void onResume() {
mapView.onResume();
super.onResume();
}
@Override
protected void onDestroy() {
locationClient.stop(); // 退出時停止定位
baiduMap.setMyLocationEnabled(false); // 關閉定位圖層
mapView.onDestroy();
mapView = null;
super.onDestroy();
}
}
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="intvehapp.intvehapp.BaiDuMapActivity">
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true" />
</RelativeLayout>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application ...>
<activity android:name=".BaiDuMapActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 百度 API_KEY,請替換為自己在開放平台申請的值 -->
<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" />
</application>
完成這三部分,即可成功定位,效果如下:

LocationClient 必須在主線程中聲明,建構時需要傳入 Context,建議使用 getApplicationContext() 取得全進程有效的物件。
public LocationClient mLocationClient = null;
public BDLocationListener myListener = new MyLocationListener();
public void onCreate() {
mLocationClient = new LocationClient(getApplicationContext());
mLocationClient.registerLocationListener(myListener);
}
private void initLocation() {
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationMode.Hight_Accuracy); // 定位模式
option.setCoorType("bd09ll"); // 回傳座標系,預設 gcj02
option.setScanSpan(1000); // 定位間隔,需 ≥1000ms 才有效
option.setIsNeedAddress(true); // 是否需要地址資訊
option.setOpenGps(true); // 是否使用 GPS
option.setLocationNotify(true); // GPS 有效時按 1 秒頻率輸出結果
option.setIsNeedLocationDescribe(true); // 位置語義化描述
option.setIsNeedLocationPoiList(true); // 是否需要周邊 POI
option.setIgnoreKillProcess(false); // stop 時是否殺死定位進程
option.setEnableSimulateGps(false); // 是否過濾 GPS 模擬結果
mLocationClient.setLocOption(option);
}
三種定位模式的差異:
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("\nlongitude : ").append(location.getLongitude());
sb.append("\nradius : ").append(location.getRadius());
if (location.getLocType() == BDLocation.TypeGpsLocation) {
sb.append("\nspeed : ").append(location.getSpeed()); // 公里/小時
sb.append("\nsatellite : ").append(location.getSatelliteNumber());
sb.append("\nheight : ").append(location.getAltitude()); // 公尺
sb.append("\ndirection : ").append(location.getDirection());
sb.append("\naddr : ").append(location.getAddrStr());
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
sb.append("\naddr : ").append(location.getAddrStr());
sb.append("\noperators : ").append(location.getOperators());
}
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("BaiduLocationApiDemo", sb.toString());
}
}
BDLocation 封裝了定位結果,透過 getLocType() 可取得狀態碼。常見取值:
若定位始終失敗,記下這個回傳碼,到百度 LBS 開放平台論壇對應版塊交流會更快找到答案。
mLocationClient.start();
start() 啟動定位,stop() 停止定位。呼叫 start() 後等待回調即可。若是單次定位場景,收到結果後直接 stop();之後想再定位,重新 start() 就好。若想完全掌控時機,也可以在 start() 之後依自身邏輯呼叫 requestLocation() 主動觸發。
位置提醒最多觸發 3 次,之後不再提醒。若需重新提醒或修改座標,可再次呼叫 SetNotifyLocation():
mNotifyer = new NotifyLister();
// 參數依次為:緯度、經度、距離範圍、座標系類型(gcj02 / gps / bd09 / bd09ll)
mNotifyer.SetNotifyLocation(42.032496, 113.312989, 3000, "gps");
mLocationClient.registerNotify(mNotifyer);
public class NotifyLister extends BDNotifyListener {
public void onNotify(BDLocation mlocation, float distance) {
mVibrator01.vibrate(1000); // 振動提醒已抵達設定位置附近
}
}
// 取消位置提醒
mLocationClient.removeNotifyEvent(mNotifyer);
理清職責之後,整個 SDK 的結構就非常清楚了:
實作過程中常見的問題包括地圖不顯示、定位失敗、根本不進入回呼函數等。網路上的解法五花八門,但未必對症。排查時優先檢查兩件事:API_KEY 是否正確、LocationClient 是否建立於主線程。另外別忽略 SDK 版本問題——百度定位 SDK 迭代很快,舊教學中的類可能早已被替換。實在卡住時,直接把官方 Demo 移植過來是最省時間的做法。
自訂 View 密碼輸入框的完整實作思路
設計準則 寫自訂 View 時有一條值得奉行的原則:把凡是會影響外觀與行為的屬性全部暴露出來,讓使用者可以透過 XML 添加和設置樣式,透過元素屬性控制外觀與行為,並提供
HBase Thrift2 CPU 使用率過高問題分析
HBase Thrift2 CPU 使用率過高問題分析 現象:外部連線 9090 連接埠時經常逾時,但 telnet 連接埠測試可成功。以 top 觀察,可看到部分 J
Notification 通知欄訊息實作(含自訂版面)
一個很典型的場景:使用者開啟 Activity 後按下 Home 鍵,此時流程會走 onPause() → onStop(),介面不可見。我們就在這個時機送一則 No
挖掘藍牙隱藏 API:用反射實作配對與解除配對
上一篇講了 Android 藍牙的基本用法,這次我們再往下挖一層,看看藍牙相關的隱藏 API。用過 Android 系統設定的人都知道,藍牙搜尋到裝置後可以進行「配對」與