編輯:關於 Android 程式設計
最近在處理百度地圖的即時路線繪製,踩到不少問題:定位漂移導致軌跡偏移;人明明沒動,路線卻一直畫出去。百度鷹眼的線路糾偏效果個人感覺一般,甚至出現過偏移兩百公尺的點它也沒修正回來的情況。官方 demo 與範例程式碼又實在太「範例」,讓人摸不著頭緒。最後決定自己寫一套糾偏邏輯。
因為即時繪製的場景都在室外,所以只採用 GPS 定位,不用無線網路定位,這樣偏移一兩百公尺的點基本上不會出現。
第二個問題是等紅綠燈時人是靜止的,但定位仍可能漂移。這部分改用手機感應器判斷是否移動:只有在確認人真的在動時,才把新位置納入軌跡。
方向確定後,功能可以拆成六個模組:
整體判斷順序如下:
這裡的門檻值(1 公尺、90 公尺、前 10 個點)都是實測調出來的经验值,實際專案可依 GPS 精度與使用情境調整。
以下程式碼假設你已具備一定的百度地圖開發基礎。註:我使用的是 3.7.3 版 jar 包,若換成其他版本,可能會出現地圖初始化失敗的問題,這點要特別留意。
package com.example.baidutext;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.View;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.utils.DistanceUtil;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class MainActivity extends Activity {
private MapView map_v;
private BaiduMap BaiDuMap;
private LocationClient locationClient;
private BitmapDescriptor bitmap, StartBitmap, EndBitmap;
private boolean isFirstLoc = true;
private boolean isGetRoute = false;
private boolean isGetNewRoute = true;
/** 定位位置資料,多線程會同時修改,需注意同步 */
private List<LatLng> pointList = new ArrayList<LatLng>();
protected MapStatusUpdate msUpdate = null;
protected OverlayOptions overlay, StartOverlay, EndOverlay;
private PolylineOptions polyline = null;
/** 加速度感應器 */
private SensorManager sm = null;
private Acc acc = new Acc();
/** 距離閾值(公尺) */
private final Double MaxDistance = 90.00;
private final Double MinDistance = 2.0;
public static PowerManager.WakeLock wakeLock = null;
private PowerReceiver powerReceiver = new PowerReceiver();
private LatLng latLng;
/** 因距離過大而丟棄的點數 */
private int LostLoc = 0;
/** 第一次定位時丟棄的點數 */
private int FLostLoc = 0;
private RoutePlanSearch mSearch;
private LatLng ll, EndLL;
private ProgressDialog progressDialog;
private int constant = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
map_v = (MapView) findViewById(R.id.bmapView);
BaiDuMap = map_v.getMap();
bitmap = BitmapDescriptorFactory.fromResource(R.drawable.map_d);
StartBitmap = BitmapDescriptorFactory.fromResource(R.drawable.start_bitmap);
EndBitmap = BitmapDescriptorFactory.fromResource(R.drawable.end_bitmap);
mSearch = RoutePlanSearch.newInstance();
mSearch.setOnGetRoutePlanResultListener(listener);
locationClient = new LocationClient(getApplicationContext());
LocationClientOption option = new LocationClientOption();
// 只做 GPS 定位,避免網路定位帶來的百米級漂移
option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);
option.setOpenGps(true);
option.setCoorType("bd09ll");
option.setScanSpan(9000);
locationClient.setLocOption(option);
locationClient.registerLocationListener(new BDLocationListener() {
@Override
public void onReceiveLocation(BDLocation location) {
ll = new LatLng(location.getLatitude(), location.getLongitude());
progressDialog.dismiss();
if (isFirstLoc || isGetRoute) {
if (!isGetRoute) {
MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
BaiDuMap.animateMapStatus(u);
}
isFirstLoc = false;
drawRealtimePoint(ll);
} else {
showRealtimeTrack(location);
}
}
});
locationClient.start();
acquireWakeLock();
}
/** 即時軌跡:先糾偏,通過檢查才畫線 */
private void showRealtimeTrack(BDLocation location) {
LatLng newPoint = new LatLng(location.getLatitude(), location.getLongitude());
if (IsMove(newPoint, location)) {
if (constant < pointList.size()) {
if (DistanceUtil.getDistance(pointList.get(constant + 1), newPoint) > 1) {
constant++;
}
}
drawRealtimePoint(newPoint);
}
}
/** 畫出即時位置與完整軌跡 */
private void drawRealtimePoint(LatLng point) {
latLng = point;
overlay = new MarkerOptions()
.position(point)
.icon(bitmap)
.zIndex(9);
if (pointList.size() >= 2 && pointList.size() <= 100000) {
polyline = new PolylineOptions()
.width(10)
.color(Color.RED)
.points(pointList);
}
addMarker();
}
private void addMarker() {
if (null != msUpdate) {
BaiDuMap.setMapStatus(msUpdate);
}
if (null != polyline) BaiDuMap.addOverlay(polyline);
if (null != overlay) BaiDuMap.addOverlay(overlay);
if (null != StartOverlay) BaiDuMap.addOverlay(StartOverlay);
if (null != EndOverlay) BaiDuMap.addOverlay(EndOverlay);
}
/** 核心:判斷這個點該不該收 */
private boolean IsMove(LatLng latLng, BDLocation location) {
if (pointList.size() >= 1) {
Double dis = DistanceUtil.getDistance(pointList.get(pointList.size() - 1), latLng);
// 手機靜止時,判定採集點無效,直接拋棄
if (!acc.is_Acc && acc.IsRun) {
acc.IsRun = false;
return false;
}
// 第一次定位的容錯處理
if (FLostLoc < 10) {
FLostLoc = FLostLoc + 1;
if (dis > 10 && FLostLoc < 6) {
// 距離大於十公尺且被拋棄數量少於 5 個,可能是定位失敗
pointList.clear();
pointList.add(latLng);
return false;
}
if (dis > 0 && dis < 10 && FLostLoc >= 6) {
// 距離在十公尺內,代表使用者正在移動
FLostLoc = 11;
}
}
// 漂移判斷:太近則拋棄,太遠則取中點
if (dis <= MinDistance || dis >= MaxDistance) {
if (LostLoc >= 4) {
Double newLat = (latLng.latitude + pointList.get(pointList.size() - 1).latitude) / 2;
Double newLon = (latLng.longitude + pointList.get(pointList.size() - 1).longitude) / 2;
latLng = new LatLng(newLat, newLon);
} else {
LostLoc = LostLoc + 1;
return false;
}
}
LostLoc = 0;
acc.is_Acc = false;
}
pointList.add(latLng);
return true;
}
/** 開始路線規劃 */
private void StartRoutePlan() {
progressDialog.setTitle("路線規劃");
progressDialog.setMessage("正在規劃路線請稍後…");
progressDialog.show();
if (pointList != null && pointList.size() > 0) pointList.clear();
PlanNode stNode = PlanNode.withLocation(ll);
StartOverlay = new MarkerOptions().position(ll).icon(StartBitmap).zIndex(9);
PlanNode enNode = PlanNode.withLocation(EndLL);
EndOverlay = new MarkerOptions().position(EndLL).icon(EndBitmap).zIndex(9);
mSearch.walkingSearch((new WalkingRoutePlanOption()).from(stNode).to(enNode));
isGetRoute = true;
}
/** 偵測到偏離路線時詢問使用者 */
private void IsGetNewRoute() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("路線偏移");
builder.setMessage("您已偏移路線,是否重新規劃路線?");
builder.setPositiveButton("重新規劃", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
StartRoutePlan();
dialog.dismiss();
}
});
builder.setNegativeButton("按原規劃", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
isGetNewRoute = false;
}
private final OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {
@Override
public void onGetWalkingRouteResult(WalkingRouteResult result) {
progressDialog.dismiss();
if (result == null || result.getRouteLines() == null) {
Toast.makeText(MainActivity.this, "規劃失敗", Toast.LENGTH_SHORT).show();
return;
}
constant = 0;
isGetNewRoute = true;
isGetRoute = false;
// 依規劃結果的每一段 step 還原成軌跡點
pointList.clear();
// ... 此處依 WalkRouteLine 的 step 內容重建 pointList
drawRealtimePoint(ll);
}
@Override
public void onGetTransitRouteResult(TransitRouteResult result) { }
@Override
public void onGetDrivingRouteResult(DrivingRouteResult result) { }
@Override
public void onGetBikingRouteResult(BikingRouteResult result) { }
};
/** 申請電源鎖,避免定位服務被系統休眠中斷 */
private void acquireWakeLock() {
if (null == wakeLock) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
getClass().getName());
}
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(powerReceiver, filter);
}
private void releaseWakeLock() {
unregisterReceiver(powerReceiver);
}
@Override
protected void onResume() {
super.onResume();
map_v.onResume();
sm.registerListener(acc, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
acquireWakeLock();
}
/** 把軌跡暫存到 SharedPreferences,避免 Activity 重建後遺失 */
private boolean saveArray() {
SharedPreferences sp = getSharedPreferences("lat", Context.MODE_APPEND);
SharedPreferences.Editor editor = sp.edit();
editor.remove("Status_size");
editor.putInt("Status_size", pointList.size());
for (int i = 0; i < pointList.size(); i++) {
editor.remove("lat_" + i);
editor.putString("lat_" + i, pointList.get(i).latitude + "");
editor.remove("lon_" + i);
editor.putString("lon_" + i, pointList.get(i).longitude + "");
}
return editor.commit();
}
/** 寫入除錯日誌 */
private void save(String content) {
try {
FileOutputStream outputStream = openFileOutput("Log.log", Activity.MODE_APPEND);
outputStream.write((content + "\n").getBytes());
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getStringDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.format(currentTime);
}
}
這個類別負責依螢幕的開關來取得與釋放 WakeLock。螢幕關閉時取得鎖,確保背景定位不被中斷;螢幕打開時釋放,避免無謂耗電。
public class PowerReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
final String action = intent.getAction();
// 按下電源鍵,關閉螢幕
if (Intent.ACTION_SCREEN_OFF.equals(action)) {
if (null != MainActivity.wakeLock && !(MainActivity.wakeLock.isHeld())) {
MainActivity.wakeLock.acquire();
}
} else if (Intent.ACTION_SCREEN_ON.equals(action)) {
// 按下電源鍵,打開螢幕
if (null != MainActivity.wakeLock && MainActivity.wakeLock.isHeld()) {
MainActivity.wakeLock.release();
}
}
}
}
這個類別取得加速度感應器的值,透過波峰波谷的差值與兩個波峰之間的時間間隔來判斷手機是否處於移動狀態——原理和計步器一致。
核心邏輯是動態閾值:先記錄波峰與波谷的差值,收集到 4 筆之後取平均並「梯化」成一個固定閾值,避免在不同路面、不同使用者身上失效。判定條件是「連續偵測到 4 次以上符合條件的波峰」,才認定為走路,這樣可以有效過濾掉手抖造成的誤判。
public class Acc implements SensorListener {
private float gravityNew = 0; // 目前感應器的值
private float gravityOld = 0; // 上次感應器的值
private long timeOfThisPeak = 0; // 本次波峰的時間
private long timeOfLastPeak = 0; // 上次波峰的時間
private long timeOfNow = 0;
private float peakOfWave = 0; // 波峰值
private float valleyOfWave = 0; // 波谷值
private float ThreadValue = (float) 2.0; // 初始閾值
private final float initialValue = (float) 1.3; // 動態閾值的計算基準
private boolean lastStatus = false; // 上一點是上升還是下降
private boolean isDirectionUp = false; // 是否上升
private int continueUpCount = 0; // 持續上升次數
private int continueUpFormerCount = 0; // 上一輪的持續上升次數
/** 是否偵測到移動 */
public boolean is_Acc = false;
private int tempCount = 0;
private final int valueNum = 4;
private final float[] tempValue = new float[valueNum];
private int CountValue = 0;
/** 感應器是否在運行 */
public boolean IsRun = false;
@Override
public void onAccuracyChanged(int sensor, int accuracy) {
}
@Override
public void onSensorChanged(int sensor, float[] values) {
IsRun = true;
if (sensor == Sensor.TYPE_ACCELEROMETER) {
gravityNew = (float) Math.sqrt(
values[0] * values[0] + values[1] * values[1] + values[2] * values[2]);
DetectorNewStep(gravityNew);
}
}
/**
* 檢測步子
* 1. 傳入 sensor 的資料
* 2. 若偵測到波峰,且符合時間差與閾值條件,判定為一步
* 3. 符合時間差條件、波峰波谷差值大於 initialValue 時,把差值納入閾值計算
*/
public void DetectorNewStep(float values) {
if (gravityOld == 0) {
gravityOld = values;
} else {
if (DetectorPeak(values, gravityOld)) {
timeOfLastPeak = timeOfThisPeak;
timeOfNow = System.currentTimeMillis();
if ((timeOfNow - timeOfLastPeak) >= 250
&& (peakOfWave - valleyOfWave >= ThreadValue)) {
timeOfThisPeak = timeOfNow;
// 兩步間隔超過 40 秒則重新計數
if ((timeOfNow - timeOfLastPeak) > 40000) {
CountValue = 0;
} else {
CountValue++;
}
// 連續搖晃 4 下以上才判定為走路
if (CountValue >= 4) is_Acc = true;
}
if (timeOfNow - timeOfLastPeak >= 250
&& (peakOfWave - valleyOfWave >= initialValue)) {
timeOfThisPeak = timeOfNow;
ThreadValue = Peak_Valley_Thread(peakOfWave - valleyOfWave);
}
}
}
gravityOld = values;
}
/**
* 檢測波峰,判斷條件:
* 1. 目前點為下降趨勢(isDirectionUp 為 false)
* 2. 之前的點為上升趨勢(lastStatus 為 true)
* 3. 到波峰為止持續上升大於等於 4 次,或波峰值落在 20~40 區間
* 同時記錄波谷值,作為下一次波峰的對比基準
*/
public boolean DetectorPeak(float newValue, float oldValue) {
lastStatus = isDirectionUp;
if (newValue >= oldValue) {
isDirectionUp = true;
continueUpCount++;
} else {
continueUpFormerCount = continueUpCount;
continueUpCount = 0;
isDirectionUp = false;
}
if (!isDirectionUp && lastStatus
&& (continueUpFormerCount >= 4 || (oldValue >= 20 && oldValue <= 40))) {
peakOfWave = oldValue;
return true;
} else if (!lastStatus && isDirectionUp) {
valleyOfWave = oldValue;
return false;
}
return false;
}
/** 透過波峰波谷差值計算閾值,記錄 4 筆後取平均 */
public float Peak_Valley_Thread(float value) {
float tempThread = ThreadValue;
if (tempCount < valueNum) {
tempValue[tempCount] = value;
tempCount++;
} else {
tempThread = averageValue(tempValue, valueNum);
for (int i = 1; i < valueNum; i++) {
tempValue[i - 1] = tempValue[i];
}
tempValue[valueNum - 1] = value;
}
return tempThread;
}
/** 計算平均並把閾值梯化到固定區間 */
public float averageValue(float[] value, int n) {
float ave = 0;
for (int i = 0; i < n; i++) {
ave += value[i];
}
ave = ave / valueNum;
if (ave >= 8) ave = (float) 4.3;
else if (ave >= 7 && ave < 8) ave = (float) 3.3;
else if (ave >= 4 && ave < 7) ave = (float) 2.3;
else if (ave >= 3 && ave < 4) ave = (float) 2.0;
else ave = (float) 1.3;
return ave;
}
}
以上就是整套即時軌跡繪製與糾偏的實作思路,若還有其他問題歡迎留言討論。
一篇搞懂 Android SDK 目錄結構與版本號的區別
總有人問:Tools、Build-Tools、Platform-Tools 到底有什麼區別,各自是幹嘛用的?今天就把 SDK 目錄做個系統性的梳理。SDK 目錄結構add
自定義控件實戰(四):打造通訊錄字母快速索引欄 QuickIndexBar
自定義View通訊錄字母快速索引 在 Android 日常開發中,我們經常在聯繫人界面看到側邊的字母導航欄。當用戶點擊某個字母時,列表會依據漢字的首字母拼音快速定位到對
Android 音訊開發(七):深入剖析 OpenSL ES API 的核心設計
這是《Android 音訊開發》系列文章的第七篇。上一篇已經從整體角度介紹了 OpenSL ES API 的基本概況,說明這個框架具備哪些特性、能做什麼、不能做什麼。本篇
java/android 設計模式學習筆記(17):策略模式
這篇博客我們來介紹策略模式(Strategy Pattern,也叫 Policy Pattern),它同樣屬於行為型模式之一。通常在軟件開發中,我們為一個功能可能會設計多