起始位置分别为北京,上海。效果如图
自定义两个地名,进行地理编码,实现导航。
1 #import "MapViewController.h" 2 #import <MapKit/MapKit.h> 3 4 @interface MapViewController () 5 6 @property (nonatomic, strong) CLGeocoder *geocoder; 7 8 @end 9 10 @implementation MapViewController 11 12 //懒加载 13 - (CLGeocoder *)geocoder { 14 if (!_geocoder) { 15 _geocoder = [[CLGeocoder alloc] init]; 16 } 17 return _geocoder; 18 } 19 20 - (void)viewDidLoad { 21 [super viewDidLoad]; 22 [self.geocoder geocodeAddressString:@"北京" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) { 23 CLPlacemark *beginMark = [placemarks firstObject]; 24 [self.geocoder geocodeAddressString:@"上海" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) { 25 CLPlacemark *endMark = [placemarks firstObject]; 26 [self beginWithMarks:(CLPlacemark *)beginMark andMark:(CLPlacemark *)endMark]; 27 28 }]; 29 }]; 30 } 31 //自定义导航方法的实现 32 - (void)beginWithMarks:(CLPlacemark *)beginMark andMark:(CLPlacemark *)endMark { 33 //创建openMapsWithItems方法所需数组;因为没有直接创建CLPlacemark类的对象,所以使用上面地理编码的方法间接创建出CLPlacemark类的对象 34 MKPlacemark *MKmarkB = [[MKPlacemark alloc] initWithPlacemark:beginMark]; 35 MKMapItem *beginI = [[MKMapItem alloc] initWithPlacemark:MKmarkB]; 36 37 MKPlacemark *MKmarkD = [[MKPlacemark alloc] initWithPlacemark:endMark]; 38 MKMapItem *endI = [[MKMapItem alloc] initWithPlacemark:MKmarkD]; 39 //起点和终点 40 NSArray *array = @[beginI,endI]; 41 //创建openMapsWithItems方法所需字典 42 NSDictionary *dict = @{//导航方式 43 MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving, 44 //地图模式 45 MKLaunchOptionsMapTypeKey : @(MKMapTypeHybrid), 46 //是否显示交通 47 MKLaunchOptionsShowsTrafficKey : @(YES) 48 }; 49 //只需记住该行方法,从下往上推,用到什么创建什么 50 [MKMapItem openMapsWithItems:array launchOptions:dict]; 51 } 52 53 @end
时间: 2024-10-06 12:17:10