【实现功能】:
1.展示简单地图
2.显示用户当前位置
3.控制视图大小
4.大头针点击显示信息
5.放置目的地大头针
6.当前位置与目的地连线
【实现步骤】
1.导入两个需要的框架:CoreLocation.framework和MapKit.framework
2.引入头文件:
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
3.需要两个类的变量,这里定义为属性:
@property (nonatomic, retain)MKMapView *mapView;
@property (nonatomic, retain)CLLocationManager *locaManager;
4.别忘了接受协议
@interface ViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
5.OK开始上代码
1 - (void)viewDidLoad{ 2 [super viewDidLoad]; 3 4 //初始化位置管理 5 self.locaManager = [[CLLocationManager alloc] init]; 6 //如果设备在iOS8及以上,得先弹框让用户授权,才能获得定位权限 7 if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) { 8 [self.locaManager requestWhenInUseAuthorization]; 9 } 10 //设置代理 11 self.locaManager.delegate = self; 12 //开始定位 13 [self.locaManager startUpdatingLocation]; 14 15 16 //初始化地图视图 17 self.mapView = [[MKMapView alloc] initWithFrame:self.view.frame]; 18 //设置地图样式为基本样式(这里有三种样式) 19 self.mapView.mapType = MKMapTypeStandard; 20 //是否显示当前位置 21 self.mapView.showsUserLocation = YES; 22 //设置代理 23 self.mapView.delegate = self; 24 [self.view addSubview:self.mapView]; 25 }
代理方法的实现
#pragma mark -- mapViewDelegate - (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView{ NSLog(@"加载完毕"); } - (void)mapViewWillStartLocatingUser:(MKMapView *)mapView{ NSLog(@"将要获取用户位置"); } - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{ //点击大头针,出现信息 userLocation.title = @"丁健"; userLocation.subtitle = @"dingjianjaja"; //让地图视图转移到用户当前位置 [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES]; //设置精度,以及显示用户所在地 MKCoordinateSpan span = MKCoordinateSpanMake(1, 1);//比例尺为1:10^5,1厘米代表1公里 MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, span); [mapView setRegion:region animated:YES]; }
6.运行
发现不显示用户位置,原因是在iOS8以后程序使用定位有三种状态,即试用期间/始终/永不,所以我们需要在plist文件中配置:试用期间或者始终
NSLocationWhenInUseUsageDescription
简单的展示地图自己位置就完成了,下面会继续加入目的地大头针,以及连接当前位置与目的地,并计算直线距离的功能。
1.要想在地图上连接2个点,首先需要将两个点加入到一个数组中
起点:
1 CLLocationCoordinate2D coord1; 2 coord1.latitude = userLocation.location.coordinate.latitude; 3 coord1.longitude = userLocation.location.coordinate.longitude; 4 5 coords[0] = coord1;
终点:
1 coords[1] = coord;
coords数组中有两个元素
下面开始画线链接
1 MKPolyline *line = [MKPolyline polylineWithCoordinates:coords count:2];//执行画线方法; 2 [self.mapView addOverlay: line];
还没完,最后要实现代理方法确定画线的样式
1 #pragma mark 地图两点画线代理方法 2 - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay 3 { 4 if ([overlay isKindOfClass:[MKPolyline class]]) 5 { 6 MKPolylineView *lineview=[[MKPolylineView alloc] initWithOverlay:overlay]; 7 lineview.strokeColor=[[UIColor blueColor] colorWithAlphaComponent:0.5]; 8 lineview.lineWidth=2.0; 9 10 return lineview; 11 }else{ 12 return nil; 13 } 14 }
OK完成效果如图:
计算两点距离
//计算距离 CLLocationDistance meters=[self.currentLocation distanceFromLocation:loc];
通过经纬度编码为地名
1 [_geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray *placemarks, NSError *error) { 2 CLPlacemark *placemark=[placemarks firstObject]; 3 NSString *str = [placemark.addressDictionary valueForKey:@"Name"]; 4 _destinationLocalLabel.text = [NSString stringWithFormat:@"目的地:%@",str]; 5 }];
完整代码:
1 // 2 // ViewController.m 3 // MapDemo 4 // 5 // Created by dingjianjaja on 15/12/11. 6 // Copyright © 2015年 dingjianjaja. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 #import <MapKit/MapKit.h> 11 #import <CoreLocation/CoreLocation.h> 12 @interface ViewController ()<CLLocationManagerDelegate,MKMapViewDelegate> 13 { 14 CLLocationCoordinate2D coords[2]; 15 } 16 @property (nonatomic, retain)MKMapView *mapView; 17 @property (nonatomic, retain)CLLocationManager *locaManager; 18 19 @property (nonatomic, retain)CLLocation *currentLocation; 20 /** 21 * 放置大头针按钮 22 */ 23 @property (nonatomic, retain)UIButton *setPosationBtn; 24 /** 25 * 经度输入框 26 */ 27 @property (nonatomic, retain)UITextField *longitudeText; 28 /** 29 * 纬度输入框 30 */ 31 @property (nonatomic, retain)UITextField *latitudeText; 32 /** 33 * 画线点的数组 34 */ 35 @property (nonatomic, retain)NSMutableArray *pointArr; 36 /** 37 * 当前地点 38 */ 39 @property (nonatomic, retain)UILabel *currentLocalLabel; 40 /** 41 * 目的地地点 42 */ 43 @property (nonatomic, retain)UILabel *destinationLocalLabel; 44 /** 45 * 相距多远 46 */ 47 @property (nonatomic, retain)UILabel *distenceLabel; 48 49 @property (nonatomic, retain)CLGeocoder *geocoder; 50 @end 51 52 @implementation ViewController 53 54 - (NSArray *)pointArr{ 55 if (!_pointArr) { 56 _pointArr = [NSMutableArray array]; 57 } 58 return _pointArr; 59 } 60 61 - (void)viewDidLoad{ 62 [super viewDidLoad]; 63 64 //初始化位置管理 65 self.locaManager = [[CLLocationManager alloc] init]; 66 //如果设备在iOS8及以上,得先弹框让用户授权,才能获得定位权限 67 if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) { 68 [self.locaManager requestWhenInUseAuthorization]; 69 } 70 //设置代理 71 self.locaManager.delegate = self; 72 //开始定位 73 [self.locaManager startUpdatingLocation]; 74 75 76 //初始化地图视图 77 self.mapView = [[MKMapView alloc] initWithFrame:self.view.frame]; 78 //设置地图样式为基本样式(这里有三种样式) 79 self.mapView.mapType = MKMapTypeStandard; 80 //是否显示当前位置 81 self.mapView.showsUserLocation = YES; 82 //设置代理 83 self.mapView.delegate = self; 84 [self.view addSubview:self.mapView]; 85 86 //放置大头针按钮 87 _setPosationBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 88 _setPosationBtn.frame = CGRectMake(10, 100, 100, 30); 89 [_setPosationBtn setTitle:@"放置大头针" forState:UIControlStateNormal]; 90 _setPosationBtn.backgroundColor = [UIColor orangeColor]; 91 _setPosationBtn.alpha = 0.4; 92 [_setPosationBtn addTarget:self action:@selector(setPositionBtnClick) forControlEvents:UIControlEventTouchUpInside]; 93 [self.view addSubview:_setPosationBtn]; 94 95 //经纬度文本框 96 _longitudeText = [[UITextField alloc] initWithFrame:CGRectMake(10, 20, 100, 30)]; 97 _longitudeText.backgroundColor = [UIColor grayColor]; 98 _longitudeText.alpha = 0.5; 99 [self.view addSubview:_longitudeText]; 100 101 _latitudeText = [[UITextField alloc] initWithFrame:CGRectMake(10, 60, 100, 30)]; 102 _latitudeText.backgroundColor = [UIColor grayColor]; 103 _latitudeText.alpha = 0.5; 104 [self.view addSubview:_latitudeText]; 105 106 107 108 //当前地点 109 _currentLocalLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_longitudeText.frame) + 10, 20, 247, 30)]; 110 _currentLocalLabel.backgroundColor = [UIColor grayColor]; 111 _currentLocalLabel.text = @"当前地点:"; 112 _currentLocalLabel.font = [UIFont systemFontOfSize:12]; 113 [self.view addSubview:_currentLocalLabel]; 114 115 //目标地点 116 _destinationLocalLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_longitudeText.frame) + 10, 60, 247, 30)]; 117 _destinationLocalLabel.backgroundColor = [UIColor grayColor]; 118 _destinationLocalLabel.text = @"目标地点:"; 119 _destinationLocalLabel.font = [UIFont systemFontOfSize:12]; 120 [self.view addSubview:_destinationLocalLabel]; 121 122 //距离 123 _distenceLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_setPosationBtn.frame) + 10, 100, 247, 30)]; 124 _distenceLabel.backgroundColor = [UIColor grayColor]; 125 _distenceLabel.text = @"相距距离:"; 126 _distenceLabel.font = [UIFont systemFontOfSize:12]; 127 [self.view addSubview:_distenceLabel]; 128 129 _geocoder=[[CLGeocoder alloc]init]; 130 131 } 132 133 #pragma mark 根据坐标取得地名 134 -(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{ 135 //反地理编码 136 CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude]; 137 [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { 138 CLPlacemark *placemark=[placemarks firstObject]; 139 NSString *str = [placemark.addressDictionary valueForKey:@"Name"]; 140 NSLog(@"详细信息:%@",str); 141 }]; 142 } 143 144 145 146 - (void)setPositionBtnClick{ 147 NSLog(@"放置大头针"); 148 149 150 //创建CLLocation 设置经纬度 151 CLLocation *loc = [[CLLocation alloc]initWithLatitude:[[self.latitudeText text] floatValue] longitude:[[self.longitudeText text] floatValue]]; 152 CLLocationCoordinate2D coord = [loc coordinate]; 153 //创建标题 154 NSString *titile = [NSString stringWithFormat:@"%f,%f",coord.latitude,coord.longitude]; 155 MyPoint *myPoint = [[MyPoint alloc] initWithCoordinate:coord andTitle:titile]; 156 //添加标注 157 [self.mapView addAnnotation:myPoint]; 158 159 //放大到标注的位置 160 MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 80000, 80000); 161 [self.mapView setRegion:region animated:YES]; 162 163 //声明一个数组 用来存放画线的点 164 165 coords[1] = coord; 166 MKPolyline *line = [MKPolyline polylineWithCoordinates:coords count:2];//执行画线方法; 167 [self.mapView addOverlay: line]; 168 169 170 //计算距离 171 CLLocationDistance meters=[self.currentLocation distanceFromLocation:loc]; 172 _distenceLabel.text = [NSString stringWithFormat:@"相距距离:%.2f千米",meters/1000]; 173 174 [_geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray *placemarks, NSError *error) { 175 CLPlacemark *placemark=[placemarks firstObject]; 176 NSString *str = [placemark.addressDictionary valueForKey:@"Name"]; 177 _destinationLocalLabel.text = [NSString stringWithFormat:@"目的地:%@",str]; 178 }]; 179 180 181 182 } 183 184 #pragma mark 地图两点画线代理方法 185 - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay 186 { 187 if ([overlay isKindOfClass:[MKPolyline class]]) 188 { 189 MKPolylineView *lineview=[[MKPolylineView alloc] initWithOverlay:overlay]; 190 lineview.strokeColor=[[UIColor blueColor] colorWithAlphaComponent:0.5]; 191 lineview.lineWidth=2.0; 192 193 return lineview; 194 }else{ 195 return nil; 196 } 197 } 198 199 200 201 #pragma mark -- mapViewDelegate 202 203 - (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView{ 204 NSLog(@"加载完毕"); 205 } 206 - (void)mapViewWillStartLocatingUser:(MKMapView *)mapView{ 207 NSLog(@"将要获取用户位置"); 208 } 209 210 - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{ 211 //点击大头针,出现信息 212 userLocation.title = @"丁健"; 213 214 self.currentLocation = [[CLLocation alloc] initWithLatitude:userLocation.location.coordinate.latitude longitude:userLocation.location.coordinate.longitude]; 215 NSLog(@"当前位置%@",self.currentLocation); 216 217 218 //地理反编码 219 [_geocoder reverseGeocodeLocation:self.currentLocation completionHandler:^(NSArray *placemarks, NSError *error) { 220 CLPlacemark *placemark=[placemarks firstObject]; 221 NSString *str = [placemark.addressDictionary valueForKey:@"Name"]; 222 _currentLocalLabel.text = [NSString stringWithFormat:@"当前地点:%@",str]; 223 }]; 224 225 226 //让地图视图转移到用户当前位置 227 [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES]; 228 229 CLLocationCoordinate2D coord1; 230 coord1.latitude = userLocation.location.coordinate.latitude; 231 coord1.longitude = userLocation.location.coordinate.longitude; 232 233 coords[0] = coord1; 234 //设置精度,以及显示用户所在地 235 MKCoordinateSpan span = MKCoordinateSpanMake(1, 1);//比例尺为1:10^5,1厘米代表1公里 236 MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, span); 237 [mapView setRegion:region animated:YES]; 238 } 239 240 241 - (void)didReceiveMemoryWarning { 242 [super didReceiveMemoryWarning]; 243 // Dispose of any resources that can be recreated. 244 } 245 246 @end