初次写博客,如有错误欢迎各路大神赐教,对于写博客有建议的也欢迎各位提点。
本文简单地实现了对于地图上的两个地理位置,可以画出它们之间的路线。最终效果如下图所示:
首先,加入MapKit和CoreLocation两个框架,点击所建项目,General下的Linked Frameworks and Libraries下点击加号,加入MapKit.framework和CoreLocation.framework两个框架,然后在Main.storyboard上加一个MapView,用于显示地图,并将其连线成为一个属性mapView,导入MapKit和CoreLocation的头文件。(如果没有加入框架,连线后会报错,原因是识别不了这个属性)。
获得当前位置的地理信息需要用到CLGeocoder,因此定义一个全局变量geocoder:
@property(nonatomic,strong)CLGeocoder *geocoder;
并使用懒加载的方式对其进行初始化:
-(CLGeocoder *)geocoder
{
if (!_geocoder) {
self.geocoder=[[CLGeocoder alloc]init];
}
return _geocoder;
}
在viewDidLoad里让控制器成为mapView的代理,并确定两个地点,这里确定的地点是北京和广东。然后根据位置采用地理编码获得具体的位置信息:
- (void)viewDidLoad {
[super viewDidLoad];
self.mapView.delegate=self;
NSString *address1=@"北京";
NSString *address2=@"广东";
[self.geocoder geocodeAddressString:address1 completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (error) return ;
CLPlacemark *fromPm=[placemarks firstObject];
[self.geocoder geocodeAddressString:address2 completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if(error)return ;
CLPlacemark *toPm=[placemarks firstObject];
[self addLineFrom:fromPm to:toPm];
}];
}];
}
使用addLineFrom方法添加导航路线,该方法中,在北京和广东这两个起始点放了一个大头针:-(void)addLineFrom:(CLPlacemark *)fromPm to:(CLPlacemark *)toPm
{
//1.添加2个大头针
STAnnotation *fromAnno=[[STAnnotation alloc]init];
fromAnno.coordinate=fromPm.location.coordinate;
fromAnno.title=fromPm.name;
[self.mapView addAnnotation:fromAnno];
STAnnotation *toAnno=[[STAnnotation alloc]init];
toAnno.coordinate=toPm.location.coordinate;
toAnno.title=toPm.name;
[self.mapView addAnnotation:toAnno];
//2.查找路线
//方向请求
MKDirectionsRequest *request=[[MKDirectionsRequest alloc]init];
//设置起点
MKPlacemark *sourcePm=[[MKPlacemark alloc]initWithPlacemark:fromPm];
request.source=[[MKMapItem alloc]initWithPlacemark:sourcePm];
//设置终点
MKPlacemark *destinationPm=[[MKPlacemark alloc]initWithPlacemark:toPm];
request.destination=[[MKMapItem alloc]initWithPlacemark:destinationPm];
//方向对象
MKDirections *directions=[[MKDirections alloc]initWithRequest:request];
//计算路线
[directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"总共%lu条路线",response.routes.count);
//遍历所有的路线
for (MKRoute *route in response.routes) {
//添加路线遮盖
[self.mapView addOverlay:route.polyline];
}
}];
}
这里会调用MapView的代理方法来画到航线:#pragma mark-MKMapViewDelegate
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
MKPolylineRenderer *render=[[MKPolylineRenderer alloc]initWithOverlay:overlay];
render.strokeColor=[UIColor redColor];
return render;
}
这样一条导航路线就画出来了,还需要说明一下的是:STAnnotation大头针对象是一个继承自带大头针的类,和其自带的大头针一样有3个属性:
@interface STAnnotation : NSObject<MKAnnotation>
@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@end