最近在做一個小 demo,嘗試實現軌跡記錄功能。
記錄軌跡需要不停地獲取位置並存儲到數據庫中。然而在繪制折線時,會遇到一個常見問題:在道路拐角處,折線往往直接連線,無法與實際道路貼合。本文就來分享一下我的解決方案。
我的做法是調用百度地圖的路徑規劃 API,這樣就能實現軌跡的道路貼合功能。
下面附上 demo:點擊打開鏈接
特別提醒:這個 demo 是真機上運行的,在模擬器上會報錯,下載時請注意。另外,由於各種原因,本文配圖是用手機拍攝的。
先上圖看看效果:

首先構建起點與終點的坐標節點,並發起駕駛路線檢索:
BMKPlanNode *startNode = [[BMKPlanNode alloc] init];
CLLocationCoordinate2D startCoordinate;
startCoordinate.latitude = 36.727558;
startCoordinate.longitude = 119.185956;
startNode.pt = startCoordinate;
BMKPlanNode *endNode = [[BMKPlanNode alloc] init];
CLLocationCoordinate2D endCoordinate;
endCoordinate.latitude = 36.827558;
endCoordinate.longitude = 119.385956;
endNode.pt = endCoordinate;
BMKDrivingRoutePlanOption *drivingRoutePlanOption = [[BMKDrivingRoutePlanOption alloc] init];
drivingRoutePlanOption.from = startNode;
drivingRoutePlanOption.to = endNode;
if ([_searcher drivingSearch:drivingRoutePlanOption]) {
NSLog(@"路線查找成功");
}
下面是路線檢索的代理回調方法。我們從返回的線路中取出各路段,再從每個路段中取出坐標點,最後對這些點進行畫線:
- (void)onGetDrivingRouteResult:(BMKRouteSearch *)searcher result:(BMKDrivingRouteResult *)result errorCode:(BMKSearchErrorCode)error {
BMKDrivingRouteLine *plan = (BMKDrivingRouteLine *)[result.routes objectAtIndex:0];
int size = (int)[plan.steps count];
int pointCount = 0;
// 統計總坐標點數量
for (int i = 0; i < size; i++) {
BMKDrivingStep *step = [plan.steps objectAtIndex:i];
pointCount += step.pointsCount;
}
// 依次取出所有坐標點
BMKMapPoint *points = new BMKMapPoint[pointCount];
int k = 0;
for (int i = 0; i < size; i++) {
BMKDrivingStep *step = [plan.steps objectAtIndex:i];
for (int j = 0; j < step.pointsCount; j++) {
points[k].x = step.points[j].x;
points[k].y = step.points[j].y;
k++;
}
}
NSLog(@"點的個數:(%d)", k);
// 用這些點繪制折線並添加到地圖
BMKPolyline *polyLine = [BMKPolyline polylineWithPoints:points count:pointCount];
[_mapView addOverlay:polyLine];
}
透過這種方式,軌跡就能沿著真實道路貼合顯示,而不是在拐角處生硬地直連,記錄效果自然更加精準。