添加地圖覆蓋物后還需要通過代理方法來設置覆蓋物樣式,否則是看不到效果的
簡單的UI搭建:

UI.png
演示代碼:
#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 {
// 創(chuàng)建導航對象請求,設置起始點
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];
// 創(chuàng)建導航對象
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];
}
}];
}];
}
/**
* 當設置覆蓋物的樣式時調(diào)用
*
* @param mapView 地圖視圖
* @param overlay 覆蓋物
*
* @return 覆蓋物樣式
*/
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
// 創(chuàng)建折線樣式(子類)
/*
實際這里傳遞的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;
}
效果:

res.png