包括地图显示以及运动轨迹显示
导入#import <MapKit/MapKit.h>
声明一个 MKMapView * mapView;
一个 CLLocationManager * locationManager;
声明代理MKMapViewDelegate,CLLocationManagerDelegate
初始化MKMapView
mapView.delegate = self;
mapView.userTrackingMode = MKUserTrackingModeFollow; //设置跟踪模式为跟随用户模式
[mapView setShowsUserLocation:YES]; //显示用户位置在地图
mapView.mapType = MKMapTypeStandard; //设置地图显示模式
mapView.scrollEnabled = YES; //是否允许滑动
初始化CLLocationManager
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest; //设置定位精度
locationManager.distanceFilter = 10; //设置更新location的最小距离,单位米
[locationManager requestAlwaysAuthorization]; //获取定位服务授权
[locationManager startUpdatingLocation]; // 开始定位
绘线
实现CLLocationManager的代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
for (CLLocation *newLocation in result) {
gpsPower = newLocation.horizontalAccuracy; //最低5m最大65m
NSDate *eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
//转换后的coord
CLLocationCoordinate2D coord;
//得到newLocation
//判断是不是属于国内范围,CLLocationManager获取到的是地球坐标
if (![WGS84TOGCJ02 isLocationOutOfChina:[newLocation coordinate]]) {
//转换后的coord
coord = [WGS84TOGCJ02 transformFromWGSToGCJ:[newLocation coordinate]];
}
if (fabs(howRecent) < 10.0 && newLocation.horizontalAccuracy < 40) {
// update distance
if (isStart) {
if (firstLocation) { //是否第一个Location
firstLocation = NO;
//坐标最大最小,为了最后显示全部的轨迹
minLat = coord.latitude;
maxLat = coord.latitude;
minLon = coord.longitude;
maxLon = coord.longitude;
}
if (cllocationMutableArray.count > 0) {
distance += [newLocation distanceFromLocation:cllocationMutableArray.lastObject]; //该计算为地球坐标系 单位m,测算移动距离
CLLocationCoordinate2D coords[2];
coords[0] = lastCJ02Coord;
coords[1] = coord;
[mapView addOverlay:[MKPolyline polylineWithCoordinates:coords count:2]];
}
//坐标最大最小
minLat = MIN(minLat, coord.latitude);
maxLat = MAX(maxLat, coord.latitude);
minLon = MIN(minLon, coord.longitude);
maxLon = MAX(maxLon, coord.longitude);
lastCJ02Coord = coord;
[cllocationMutableArray addObject:newLocation];
}
}
}
}
实现MKMapView的代理方法绘制相应MKPolylineView
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id < MKOverlay >)overlay
{
if ([overlay isKindOfClass:[MKPolyline class]]) {
MKPolyline *polyLine = (MKPolyline *)overlay;
MKPolylineRenderer *aRenderer = [[MKPolylineRenderer alloc] initWithPolyline:polyLine];
aRenderer.strokeColor = [UIColor greenColor];
aRenderer.lineWidth = 4;
return aRenderer;
}
return nil;
}
参考资料:
http://www.raywenderlich.com/73984/make-app-like-runkeeper-part-1
http://www.raywenderlich.com/74331/make-app-like-runkeeper-part-2
TODO:
- 根据速度绘制渐变颜色线条