标签:
只要用于获取用户位置都要取得用户授权
#import "ViewController.h"
#import <MapKit/MapKit.h>
@interface ViewController ()<MKMapViewDelegate>
@property(nonatomic,strong)UITextField*destination;
@property(nonatomic,strong)MKMapView*mapView;
@property(nonatomic,strong)CLLocationManager *mgr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.mgr=[[CLLocationManager alloc]init];
[self.mgr requestAlwaysAuthorization];
MKMapView *map=[[MKMapView alloc]init];
map.frame=self.view.bounds;
self.mapView=map;
[self.view addSubview:map];
self.mapView.delegate=self;
UITextField *field=[[UITextField alloc]init];
field.frame=CGRectMake(10, 20, 60, 30);
self.destination=field;
field.text=@"西安";
[self.view addSubview:field];
[self drawLine];
}
//划线
-(void)drawLine
{
[self.view endEditing:YES];
CLGeocoder *geo=[[CLGeocoder alloc]init];
[geo geocodeAddressString:self.destination.text completionHandler:^(NSArray *placemarks, NSError *error) {
if (placemarks.count==0||error) {
return ;
}
//获取目的地item 和当前的位置
CLPlacemark *pm=[placemarks firstObject];
MKPlacemark *mkp=[[MKPlacemark alloc]initWithPlacemark:pm];
MKMapItem *destinationItem=[[MKMapItem alloc]initWithPlacemark:mkp];
MKMapItem *userItem=[MKMapItem mapItemForCurrentLocation];
//1创建路线请求
MKDirectionsRequest*request=[[MKDirectionsRequest alloc]init];
//设置起点终点
request.source=userItem;
request.destination=destinationItem;
//创建路线管理器
MKDirections *direction=[[MKDirections alloc]initWithRequest:request];
//划线
[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
for (MKRoute*route in response.routes) {
//拿到线
MKPolyline *line=route.polyline;
//添加到地图
[self.mapView addOverlay:line];
}
}];
}];
}
-(MKOverlayRenderer*)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
//创建渲染器
MKPolylineRenderer *render=[[MKPolylineRenderer alloc]initWithOverlay:overlay];
//设置线段的颜色
render.strokeColor=[UIColor redColor];
//设置线宽
render.lineWidth=5;
return render;
}
@end
标签:
原文地址:http://www.cnblogs.com/tangranyang/p/4655801.html