#import"ViewController.h"
#import
#import"MBProgressHUD+MJ.h"
@interfaceViewController()
/**起点*/
@property(weak,nonatomic)IBOutletUITextField*startField;
/**终点*/
@property(weak,nonatomic)IBOutletUITextField*endField;
/**地理编码*/
@property(nonatomic,strong)CLGeocoder*geocoder;
- (IBAction)startNavigation;
@end
@implementationViewController
#warning geocoder懒加载
-(CLGeocoder*)geocoder
{
if(_geocoder==nil) {
_geocoder= [[CLGeocoderalloc]init];
}
return_geocoder;
}
/**
*开始导航
*/
- (IBAction)startNavigation {
//1,获取用户输入的起点终点
NSString* startStr =self.startField.text;
NSString* endStr =self.endField.text;
if(startStr ==nil||startStr.length==0||
endStr ==nil|| endStr.length==0) {
[MBProgressHUDshowError:@"请输入地址"];
return;
}
//2,利用GEO对象进行地理编码获取地标对象
//2.1获取开始位置的地标
[self.geocodergeocodeAddressString:startStrcompletionHandler:^(NSArray *_Nullableplacemarks,NSError*_Nullableerror) {
if(placemarks.count==0||error !=nil) {
[MBProgressHUDshowError:@"请输入地址"];
return;
}
//开始位置的地标
CLPlacemark* startPlacemark = [placemarksfirstObject];
//3,获得结束位置的地标
[self.geocodergeocodeAddressString:endStrcompletionHandler:^(NSArray *_Nullableplacemarks,NSError*_Nullableerror) {
if(placemarks.count==0||error !=nil) {
[MBProgressHUDshowError:@"请输入地址"];
return;
}
CLPlacemark* endPlacemark = [placemarksfirstObject];
//4,获得地标后开始导航
[selfstartNavigationWithStartPlacemark:startPlacemarkendPlacemark:endPlacemark];
}];
}];
}
/**
*利用地标位置开始设置导航
*
* @param startPlacemark开始位置的地标
* @param endPlacemark结束位置的地标
*/
-(void)startNavigationWithStartPlacemark:(CLPlacemark*)startPlacemark endPlacemark:(CLPlacemark*)endPlacemark
{
//0,创建起点
MKPlacemark* startMKPlacemark = [[MKPlacemarkalloc]initWithPlacemark:startPlacemark];
//0,创建终点
MKPlacemark* endMKPlacemark = [[MKPlacemarkalloc]initWithPlacemark:endPlacemark];
//1,设置起点位置
MKMapItem* startItem = [[MKMapItemalloc]initWithPlacemark:startMKPlacemark];
//2,设置终点位置
MKMapItem* endItem = [[MKMapItemalloc]initWithPlacemark:endMKPlacemark];
//3,起点,终点数组
NSArray* items =@[startItem ,endItem];
//4,设置地图的附加参数,是个字典
NSMutableDictionary* dictM = [NSMutableDictionarydictionary];
//导航模式(驾车,步行)
dictM[MKLaunchOptionsDirectionsModeKey] =MKLaunchOptionsDirectionsModeDriving;
//地图显示的模式
dictM[MKLaunchOptionsMapTypeKey] =MKMapTypeStandard;
//只要调用MKMapItem的open方法,就可以调用系统自带地图的导航
//Items:告诉系统地图从哪到哪
//launchOptions:启动地图APP参数(导航的模式/是否需要先交通状况/地图的模式/..)
[MKMapItemopenMapsWithItems:itemslaunchOptions:dictM];
}
@end