ios 百度地圖劃線

最近在弄百度地圖..百度地圖的坑啊

廢話不說直接上代碼

 BMKMapView *mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 70, self.view.bounds.size.width, self.view.bounds.size.height - 70)];
    self.mapView = mapView;
    [self.view addSubview:mapView];
    
    self.mapView.mapType = BMKMapTypeStandard;
    self.mapView.zoomLevel = 19;
    self.mapView.showMapScaleBar = YES;
   
//    self.mapView.compassPosition = CGPointMake(100, 100);
//    self.mapView.centerCoordinate = self.center;
    // 允許旋轉地圖
    self.mapView.rotateEnabled = YES;
    // 定位圖層自定義樣式參數
    BMKLocationViewDisplayParam *displayParam = [[BMKLocationViewDisplayParam alloc]init];
    //跟隨態旋轉角度是否生效
    displayParam.isRotateAngleValid = NO;
    //精度圈是否顯示
    displayParam.isAccuracyCircleShow = NO;
    //定位偏移量(經度)
    displayParam.locationViewOffsetX = 0;
    //定位偏移量(緯度)
    displayParam.locationViewOffsetY = 0;
    displayParam.locationViewImgName = @"walk";
    [self.mapView updateLocationViewWithParam:displayParam];
 // 必須在開始定位之前設置
    // 設置定位更新的最小距離(2M)
    self.service.distanceFilter = 10;
    // 設置定位精度
    self.service.desiredAccuracy = kCLLocationAccuracyBest;
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = BMKUserTrackingModeNone;
// 開始定位
- (IBAction)startLocation:(id)sender {
    
    // 先關閉顯示的定位圖層(一開始是定位到首都)
//    self.mapView.showsUserLocation = NO;
//    // 設置定位的狀態(普通定位模式)
//    self.mapView.userTrackingMode = BMKUserTrackingModeNone;
//    // 打開定位圖層
//    self.mapView.showsUserLocation = YES;
    
    // 清除上次路線以及狀態提示
    [self clean];
    
    self.sumTime = 0;
    self.sumDistance = 0;
    
    // 開始定位服務
    [self.service startUserLocationService];
    
//    self.mapView.showsUserLocation = YES;
//    self.mapView.userTrackingMode = BMKUserTrackingModeNone;
    
    // 設置當前地圖最合適的顯示范圍,直接顯示到用戶位置
    BMKCoordinateRegion adjustRegion = [self.mapView regionThatFits:BMKCoordinateRegionMake(self.service.userLocation.location.coordinate, BMKCoordinateSpanMake(0.02f,0.02f))];
    // 定位到指定經緯度
    [self.mapView setRegion:adjustRegion animated:YES];
    
    // 7.設置軌跡記錄狀態為:開始
    self.trail = TrailStart;
}
// 結束定位
- (IBAction)stopLocation:(id)sender {
    
    // 設置軌跡記錄狀態為:結束
    self.trail = TrailEnd;
    
    // 停止定位服務
    [self.service stopUserLocationService];
    // 關閉定位圖層
//    self.mapView.showsUserLocation = NO;
    
    // 添加終點旗幟
    if (self.startPoint) {
        self.endPoint = [self creatPointWithLocaiton:self.preLocation title:@"終點"];
    }
}
/**
 *  在將要啟動定位時,會調用此函數
 */
- (void)willStartLocatingUser {
    NSLog(@"開始定位");
}

/**
 *  在停止定位后,會調用此函數
 */
- (void)didStopLocatingUser {
    NSLog(@"停止定位");
}

/**
 *  用戶方向更新后,會調用此函數
 *  userLocation 新的用戶位置(百度坐標)
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation {
    
//    [self.mapView updateLocationData:userLocation];
//    NSLog(@"方向為————%@", userLocation.heading);
    
    // 動態更新位置數據
    [self.mapView updateLocationData:userLocation];
}

/**
 *  用戶位置更新后,會調用此函數
 *  userLocation 新的用戶位置(百度坐標)
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
   
    // 動態更新位置數據
    [self.mapView updateLocationData:userLocation];
//    NSLog(@"經度————%f,緯度————%f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
   
    // 如果精度更新的水平精準度大于10M,那么直接返回該方法
    if (userLocation.location.horizontalAccuracy > kCLLocationAccuracyHundredMeters)
        return;
    
    // GPS精度定位準確無誤,那么就來開始記錄軌跡吧
    [self startTrailRouteWithUserLocation:userLocation];

}
/**
 *  開始記錄有效軌跡
 */
- (void)startTrailRouteWithUserLocation:(BMKUserLocation *)userLocation {
    // 如果該點不是第一個點,則可以進行下面的比較運算
    if (self.preLocation) {
        // 計算本次定位數據與上次定位數據之間的時間差
        NSTimeInterval dtime = [userLocation.location.timestamp timeIntervalSinceDate:self.preLocation.timestamp];
        
        // 累計步行時間
        self.sumTime += dtime;
//        self.statusView.sumTime.text = [NSString stringWithFormat:@"%.3f",self.sumTime];
        
        // 計算本次定位點與上次定位點之間的距離
        CGFloat distance = [userLocation.location distanceFromLocation:self.preLocation];
        // (5米距離的限值,存儲到數組之中) 如果距離少于2米,則忽略本次數據直接返回該方法
        if (distance < 10) {
            NSLog(@"與前一記錄點距離小于2m,直接返回該方法");
            return;
        }
        
        // 計算本地定位點與上次定位點的方向
        if (userLocation.location.coordinate.latitude > self.preLocation.coordinate.latitude && userLocation.location.coordinate.longitude > self.preLocation.coordinate.longitude) {
            self.stateView.directionLabel.text = @"東北方向行進中";
        }
        
        if (userLocation.location.coordinate.latitude > self.preLocation.coordinate.latitude && userLocation.location.coordinate.longitude < self.preLocation.coordinate.longitude) {
            self.stateView.directionLabel.text = @"西北方向行進中";
        }
        
        if (userLocation.location.coordinate.latitude < self.preLocation.coordinate.latitude && userLocation.location.coordinate.longitude > self.preLocation.coordinate.longitude) {
            self.stateView.directionLabel.text = @"東南方向行進中";
        }
        
        if (userLocation.location.coordinate.latitude < self.preLocation.coordinate.latitude && userLocation.location.coordinate.longitude < self.preLocation.coordinate.longitude) {
            self.stateView.directionLabel.text = @"西南方向行進中";
        }
        
        
        // 累加步行距離
        self.sumDistance += distance;
        self.stateView.distanceLabel.text = [NSString stringWithFormat:@"%.3f",self.sumDistance / 1000.0];
        NSLog(@"步行總距離為:%f",self.sumDistance);
        
        // 計算移動速度
        CGFloat speed = distance / dtime;
        self.stateView.speedLabel.text = [NSString stringWithFormat:@"%.3f",speed];
        NSLog(@"步行的當前移動速度為:%.3f", speed);
        
        // 計算平均速度
//        CGFloat avgSpeed  = self.sumDistance / self.sumTime;
//        self.statusView.avgSpeed.text = [NSString stringWithFormat:@"%.3f",avgSpeed];
    }
    
    // 2. 將符合的位置點存儲到數組中
    [self.locationArrayM addObject:userLocation.location];
    self.preLocation = userLocation.location;
    
    // 3. 繪圖
    [self drawWalkPolyline];
}

/**
 *  繪制軌跡路線
 */
- (void)drawWalkPolyline
{
    // 我們保存的符合軌跡點的個數
    NSUInteger count = self.locationArrayM.count;
    
    // 手動分配存儲空間,結構體:地理坐標點,用直角地理坐標表示 X:橫坐標 Y:縱坐標
    BMKMapPoint *tempPoints = new BMKMapPoint[count];
    
    [self.locationArrayM enumerateObjectsUsingBlock:^(CLLocation *location, NSUInteger idx, BOOL *stop) {
        BMKMapPoint locationPoint = BMKMapPointForCoordinate(location.coordinate);
        tempPoints[idx] = locationPoint;
//        NSLog(@"idx = %ld,tempPoints X = %f Y = %f",idx,tempPoints[idx].x,tempPoints[idx].y);
        
        // 放置起點旗幟
        if (0 == idx && TrailStart == self.trail && self.startPoint == nil) {
            self.startPoint = [self creatPointWithLocaiton:location title:@"起點"];
        }
        
//            else { // 如果不是起點旗幟,那么肯定是中間的經過點得旗幟
            [self creatPointWithLocaiton:location title:@"過程點"];
//        }
    }];
    
    //移除原有的繪圖
    if (self.polyLine) {
        [self.mapView removeOverlay:self.polyLine];
    }
    
    // 通過points構建BMKPolyline
    self.polyLine = [BMKPolyline polylineWithPoints:tempPoints count:count];
    
    //添加路線,繪圖
    if (self.polyLine) {
        [self.mapView addOverlay:self.polyLine];
    }
    
    // 清空 tempPoints 內存
    delete []tempPoints;
    
    [self mapViewFitPolyLine:self.polyLine];   
}
/**
 *  添加一個大頭針
 */
- (BMKPointAnnotation *)creatPointWithLocaiton:(CLLocation *)location title:(NSString *)title;
{
    BMKPointAnnotation *point = [[BMKPointAnnotation alloc] init];
    point.coordinate = location.coordinate;
    point.title = title;
    [self.mapView addAnnotation:point];
    
    return point;
}

/**
 *  根據polyline(軌跡線)設置地圖范圍
 */
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(ltX , ltY);
    rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
    [self.mapView setVisibleMapRect:rect];
    self.mapView.zoomLevel = self.mapView.zoomLevel - 0.3;
}

/**
 *  清空數組以及地圖上的軌跡
 */
- (void)clean
{
    // 清空狀態欄信息
    self.stateView.distanceLabel.text = nil;
    self.stateView.speedLabel.text = nil;
    self.stateView.directionLabel.text = nil;

    //清空數組
    [self.locationArrayM removeAllObjects];
    
    //清屏,移除標注點
    if (self.startPoint) {
        [self.mapView removeAnnotation:self.startPoint];
        self.startPoint = nil;
    }
    if (self.endPoint) {
        [self.mapView removeAnnotation:self.endPoint];
        self.endPoint = nil;
    }
    if (self.polyLine) {
        [self.mapView removeOverlay:self.polyLine];
        self.polyLine = nil;
    }
    
    
}

#pragma mark - BMKMapViewDelegate

/**
 *  根據overlay生成對應的View
 *  @param mapView 地圖View
 *  @param overlay 指定的overlay
 *  @return 生成的覆蓋物View
 */
- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id<BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.fillColor = [[UIColor clearColor] colorWithAlphaComponent:0.7];
        polylineView.strokeColor = [[UIColor greenColor] colorWithAlphaComponent:0.7];
        polylineView.lineWidth = 10.0;
        return polylineView;
    }
    return nil;
}

/**
 *  只有在添加大頭針的時候會調用,直接在viewDidload中不會調用
 *  根據anntation生成對應的View
 *  @param mapView 地圖View
 *  @param annotation 指定的標注
 *  @return 生成的標注View
 */
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *annotationView = [[BMKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        
        
        if (!self.startPoint) { // 沒有起點,自然要放置起點大頭針(綠色)
            annotationView.pinColor = BMKPinAnnotationColorGreen; // 替換資源包內的圖片
//            self.statusView.stopPointLabel.text = @"YES";
        } else if (self.trail == TrailEnd) { // 點擊了結束定位,自然要放置終點大頭針(紅色)
            annotationView.pinColor = BMKPinAnnotationColorRed;
//            self.statusView.startPointLabel.text = @"YES";
        } else { // 過程大頭針(紫色)
            annotationView.pinColor = BMKPinAnnotationColorPurple;
        }
        
        // 從天上掉下效果
        annotationView.animatesDrop = YES;
        
        // 不可拖拽
        annotationView.draggable = NO;
        
        return annotationView;
    }
    return nil;
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,908評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,324評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,018評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,675評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,417評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,783評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,779評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,960評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,522評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,267評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,471評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,009評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,698評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,099評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,386評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,204評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,436評論 2 378

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,715評論 25 708
  • 一天下著綿綿細雨,心情糟糕的很。工作也不是很順心,時常想靜下新
    0海盜0閱讀 156評論 0 0
  • 開始學習javaweb 不是很喜歡這個東西,因為感覺把java和html等混雜在一起感覺怪怪的,很煩人,還是pyt...
    羋子契閱讀 326評論 0 0
  • 年輪 (一) 將一生的冷暖陰晴, 畫諸多的句號, 哪怕扭扭曲曲、歪歪斜斜。 (二) 只要不倒下, 你永遠看不到, ...
    37ba71a25722閱讀 286評論 4 6