//定位成功的回调-(void)locationManager:(CLLocationManager*)managerdidUpdateLocations:(NSArray<CLLocation*>*)locations{//获取定位成功的经纬度CLLocation*location1=locations.firstObject;CLLocationCoordinate2DcenterCoordinate2D=location1.coordinate;//为MapView添加大头针MKPointAnnotation*localAnnotstion=[[MKPointAnnotationalloc]init];localAnnotstion.coordinate=centerCoordinate2D;localAnnotstion.title=@"当前位置";[_myMapViewaddAnnotation:localAnnotstion];//设置MapView的显示区域MKCoordinateRegionregion1=MKCoordinateRegionMakeWithDistance(centerCoordinate2D,500,500);[myMapViewsetRegion:[myMapViewregionThatFits:region1]animated:YES];//定位成功就导航,设置导航路线的起点MKPlacemark*localPlacemark=[[MKPlacemarkalloc]initWithCoordinate:centerCoordinate2DaddressDictionary:nil];MKMapItem*fromItem=[[MKMapItemalloc]initWithPlacemark:localPlacemark];//createLineFromCurrentSite是我自己写的方法,用来获取导航路线和获取导航步骤//myItem指导航的终点,它实例化参考上面fromItem的实例化[selfcreateLineFromCurrentSite:fromItemto:myItem];//停止定位[managerstopUpdatingLocation];}//定位失败的回调-(void)locationManager:(CLLocationManager*)managerdidFailWithError:(NSError*)error{NSLog(@"guide error is %@",error);}
-(void)createLineFromCurrentSite:(MKMapItem*)fromItemto:(MKMapItem*)toItem{//实例化导航请求MKDirectionsRequest*request=[[MKDirectionsRequestalloc]init];//设置导航的起点和终点request.source=fromItem;request.destination=toItem;//为no时只显示一条导航路线request.requestsAlternateRoutes=NO;//实例化MKDirectionsMKDirections*directions=[[MKDirectionsalloc]initWithRequest:request];//如果当前导航好没结束,就取消下一次导航请求if(directions.calculating){[directionscancel];}//开始导航,在block里面写回调的方法[directionscalculateDirectionsWithCompletionHandler:^(MKDirectionsResponse*_Nullableresponse,NSError*_Nullableerror){if(response.routes.count==0||error){//导航失败NSLog(@"directions error is %@",error);}else{//导航成功for(MKRoute*routeinresponse.routes){for(MKRouteStep*stepinroute.steps){//打印导航的步骤NSLog(@"导航:%@",step.instructions);}//将导航路线添加到MapView上面[myMapViewaddOverlay:route.polylinelevel:MKOverlayLevelAboveRoads];}}}];}