思維導(dǎo)圖:
MApoint.png
實(shí)現(xiàn)
采納協(xié)議<MAMapViewDelegate>
@interface WBMapViewController ()<MAMapViewDelegate>
...
#pragma mark - UISetup
- (void)setupMapView{
MAMapView *_mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:_mapView];
_mapView.showsScale = NO;
// 關(guān)閉camera旋轉(zhuǎn),節(jié)省性能
_mapView.rotateCameraEnabled = NO;
_mapView.showsUserLocation = YES;
/*
- 跟蹤用戶的位置
- 可以將用戶定位在地圖的中心,并且放大地圖,有的時(shí)候,速度會(huì)有些慢!
*/
_mapView.userTrackingMode = MAUserTrackingModeFollow;
_mapView.allowsBackgroundLocationUpdates = YES;
_mapView.pausesLocationUpdatesAutomatically = NO;
// 設(shè)置代理
_mapView.delegate = self;
}
實(shí)現(xiàn)兩個(gè)代理方法
- didUpdateUserLocation
#pragma mark - delegate
/**
* @brief 位置或者設(shè)備方向更新后,會(huì)調(diào)用此函數(shù)
* @param mapView 地圖View
* @param userLocation 用戶定位信息(包括位置與設(shè)備方向等數(shù)據(jù)) 是一個(gè)固定的對(duì)象
* @param updatingLocation 標(biāo)示是否是location數(shù)據(jù)更新, YES:location數(shù)據(jù)更新 NO:heading數(shù)據(jù)更新
*/
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
// 0. 判斷 `位置數(shù)據(jù)` 是否變化 - 不一定是經(jīng)緯度變化!
if (!updatingLocation) {
return;
}
// 大概 1s 更新一次!
NSLog(@"%@ %p", userLocation.location, userLocation.location);
// 判斷起始位置是否存在
if (_startLocation == nil) {
_startLocation = userLocation.location;
// 1. 實(shí)例化大頭針
MAPointAnnotation *annotaion = [MAPointAnnotation new];
// 2. 指定坐標(biāo)位置
annotaion.coordinate = userLocation.location.coordinate;
// 3. 添加到地圖視圖
[mapView addAnnotation:annotaion];
}
// 繪制軌跡模型
[mapView addOverlay:[_sportTracking appendLocation:userLocation.location]];
}
注意:
在GPS信號(hào)好的時(shí)候,是1s調(diào)用一次代理方法.
這里得到userLocation.location位置信息的地址是相同的,所以不能通過userLocation來判斷用戶的位置是否發(fā)生變化
- viewForAnnotation:
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
if (![annotation isKindOfClass:[MAPointAnnotation class]]) {
return nil;
}
static NSString *annotaionId = @"annotaionId";
MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:annotaionId];
if (annotationView == nil) {
annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotaionId];
}
UIImage *image = _sportTracking.SportImg;
annotationView.image = image;
annotationView.centerOffset = CGPointMake(0, -image.size.height * 0.5);
return annotationView;
}
提示:
MAUserlocation 是系統(tǒng)定位用戶位置的默認(rèn)大頭針,顯示在地圖上是藍(lán)色的圓點(diǎn)
MAPointAnnotaion 是自定義的大頭針
MAUserlocation
MAPointAnnotaion
結(jié)語
添加自定義的一個(gè)起始大頭針的過程不難。實(shí)現(xiàn)兩個(gè)代理方法即可,先創(chuàng)建一個(gè)大頭針MAPointAnnotation
。在創(chuàng)建的過程中注意要給它設(shè)置一個(gè)坐標(biāo)位置同時(shí)設(shè)置一個(gè)軌跡模型. 得到MAPointAnnotation
后通過addAnnotaion:
添加給地圖View
viewForAnnotation:
返回自定義的大頭針view.
在此過程中要注意設(shè)置圖像的位置,需要讓其偏移一些,否則就蓋住了底層的定位圓點(diǎn).
annotationView.centerOffset = CGPointMake(0, -image.size.height * 0.5);