添加地图覆盖物后还需要通过代理方法来设置覆盖物样式,否则是看不到效果的
简单的UI搭建:
演示代码:
#import "ViewController.h"
#import <MapKit/MapKit.h>
@interface ViewController () <MKMapViewDelegate>
// 目标地址
@property (weak, nonatomic) IBOutlet UITextField *destination_TF;
// 地图
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
// 位置管理者
@property (strong,nonatomic) CLLocationManager *manager;
@end
@implementation ViewController
// 开始导航按钮点击事件
- (IBAction)navigationBtnClick:(id)sender {
// 创建导航对象请求,设置起始点
MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
request.source = [MKMapItem mapItemForCurrentLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
[geocoder geocodeAddressString:self.destination_TF.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (placemarks.count == 0 || error) {
return ;
}
CLPlacemark *clPlacemark = placemarks.lastObject;
MKPlacemark *mkPlacemark = [[MKPlacemark alloc]initWithPlacemark:clPlacemark];
request.destination = [[MKMapItem alloc]initWithPlacemark:mkPlacemark];
// 创建导航对象
MKDirections *directions = [[MKDirections alloc]initWithRequest:request];
// 计算坐标
[directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
return ;
}
// 遍历路线
for (MKRoute *route in response.routes) {
// 添加覆盖物(折线)
[self.mapView addOverlay:route.polyline];
}
}];
}];
}
/**
* 当设置覆盖物的样式时调用
*
* @param mapView 地图视图
* @param overlay 覆盖物
*
* @return 覆盖物样式
*/
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
// 创建折线样式(子类)
/*
实际这里传递的overlay就是polyline --> [self.mapView addOverlay:route.polyline];
*/
MKPolylineRenderer *render = [[MKPolylineRenderer alloc]initWithOverlay:overlay];
// 设置样式
render.lineWidth = 2;
render.strokeColor = [UIColor purpleColor];
return render;
}
- (void)viewDidLoad {
[super viewDidLoad];
// 授权
self.manager = [[CLLocationManager alloc]init];
if ([self.manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.manager requestWhenInUseAuthorization];
}
// 设置代理(设置覆盖物的展示样式)
self.mapView.delegate = self;
}
效果: