iOS地圖定位(定位、地理編碼與反地理編碼、mapView、大頭針、導(dǎo)航)

地圖定位.jpg

在我們的生活中現(xiàn)在很多App大多都可以獲取地理位置進(jìn)行相關(guān)的定位標(biāo)記等,有的例如餐飲App,當(dāng)我們需要訂餐時(shí),我們需要知道商家的地理位置,以方便我們能夠知道送餐人員大概需要多久可以將食物送到我們面前,當(dāng)我們需要查找某個(gè)餐廳的時(shí)候,我們只需要在搜索框中搜索相應(yīng)的店名,我們的App就能迅速的在地圖上幫我們標(biāo)注出來,以方便我們查看,當(dāng)我們需要去一個(gè)陌生的地方的時(shí)候,我們可以很輕松的通過導(dǎo)航功能,去往我們想要去得任何地方,而這些都得益于蘋果為我們提供的定位服務(wù)。

  • 首先要實(shí)現(xiàn)地圖、導(dǎo)航功能,就需要我們先熟悉定位功能,在iOS中通過Core Location框架進(jìn)行定位操作。Core Location自身可以單獨(dú)使用,和地圖開發(fā)框架MapKit完全是獨(dú)立的,但是往往地圖開發(fā)要配合定位框架使用。在Core Location中主要包含了定位、地理編碼(包括反編碼)功能。
  • 由于目前蘋果iOS系統(tǒng)最新版本為9.1,蘋果自iOS8以后如果要使用定位服務(wù),需要我們?cè)趐list文件中多添加兩個(gè)字段,其實(shí)就是提示用戶授權(quán)的用的,就是以下兩個(gè)字段:
 NSLocationWhenInUseUsageDescription  當(dāng)用戶使用的允許        
 NSLocationAlwaysUsageDescription     總是允許
 

定位服務(wù)授權(quán)狀態(tài)枚舉類型說明:

  //定位服務(wù)授權(quán)狀態(tài),返回枚舉類型:
    //kCLAuthorizationStatusNotDetermined: 用戶尚未做出決定是否啟用定位服務(wù)
    //kCLAuthorizationStatusRestricted: 沒有獲得用戶授權(quán)使用定位服務(wù),可能用戶沒有自己禁止訪問授權(quán)
    //kCLAuthorizationStatusDenied :用戶已經(jīng)明確禁止應(yīng)用使用定位服務(wù)或者當(dāng)前系統(tǒng)定位服務(wù)處于關(guān)閉狀態(tài)
    //kCLAuthorizationStatusAuthorizedAlways: 應(yīng)用獲得授權(quán)可以一直使用定位服務(wù),即使應(yīng)用不在使用狀態(tài)
    //kCLAuthorizationStatusAuthorizedWhenInUse: 使用此應(yīng)用過程中允許訪問定位服務(wù)

獲取當(dāng)前位置

ViewController.m

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()<CLLocationManagerDelegate>
@property (nonatomic,strong)CLLocationManager *locationManager;
@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化locationManger管理器對(duì)象
    CLLocationManager *locationManager=[[CLLocationManager alloc]init];
    self.locationManager=locationManager;
    
    //判斷當(dāng)前設(shè)備定位服務(wù)是否打開
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"設(shè)備尚未打開定位服務(wù)");
    }

    //判斷當(dāng)前設(shè)備版本大于iOS8以后的話執(zhí)行里面的方法
    if ([UIDevice currentDevice].systemVersion.floatValue >=8.0) {
        //持續(xù)授權(quán)
        [locationManager requestAlwaysAuthorization];
        //當(dāng)用戶使用的時(shí)候授權(quán)
        [locationManager requestWhenInUseAuthorization];
    }
    
    //或者使用這種方式,判斷是否存在這個(gè)方法,如果存在就執(zhí)行,沒有的話就忽略
    //if([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
    //   [locationManager requestWhenInUseAuthorization];
    //}
    
    //設(shè)置代理
    locationManager.delegate=self;
    //設(shè)置定位的精度
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    //設(shè)置定位的頻率,這里我們?cè)O(shè)置精度為10,也就是10米定位一次
    CLLocationDistance distance=10;
    //給精度賦值
    locationManager.distanceFilter=distance;
    //開始啟動(dòng)定位
    [locationManager startUpdatingLocation];

}
//當(dāng)位置發(fā)生改變的時(shí)候調(diào)用(上面我們?cè)O(shè)置的是10米,也就是當(dāng)位置發(fā)生>10米的時(shí)候該代理方法就會(huì)調(diào)用)
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    //取出第一個(gè)位置
    CLLocation *location=[locations firstObject];
    NSLog(@"%@",location.timestamp);
    //位置坐標(biāo)
    CLLocationCoordinate2D coordinate=location.coordinate;
    NSLog(@"經(jīng)度:%f,緯度:%f,海拔:%f,航向:%f,速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
    //如果不需要實(shí)時(shí)定位,使用完即使關(guān)閉定位服務(wù)
    //[_locationManager stopUpdatingLocation];
}


2015-11-29 13:02:48.380 地圖定位[1022:55837] 2015-11-29 05:02:06 +0000
2015-11-29 13:02:48.381 地圖定位[1022:55837] 您的當(dāng)前位置:經(jīng)度:-116.206410,緯度:39.285834,海拔:0.000000,航向:-1.000000,速度:-1.000000
2015-11-29 13:02:48.383 地圖定位[1022:55837] 2015-11-29 05:02:48 +0000
2015-11-29 13:02:48.383 地圖定位[1022:55837] 您的當(dāng)前位置:經(jīng)度:-116.206410,緯度:39.285834,海拔:0.000000,航向:-1.000000,速度:-1.000000
2015-11-29 13:03:03.081 地圖定位[1022:55837] 2015-11-29 05:03:03 +0000
2015-11-29 13:03:03.081 地圖定位[1022:55837] 您的當(dāng)前位置:經(jīng)度:-116.306410,緯度:39.285834,海拔:0.000000,航向:-1.000000,速度:-1.000000
2015-11-29 13:03:34.226 地圖定位[1022:55837] 2015-11-29 05:03:34 +0000
2015-11-29 13:03:34.226 地圖定位[1022:55837] 您的當(dāng)前位置:經(jīng)度:-116.406400,緯度:39.285834,海拔:0.000000,航向:-1.000000,速度:-1.000000
2015-11-29 13:03:57.659 地圖定位[1022:55837] 2015-11-29 05:03:57 +0000
2015-11-29 13:03:57.659 地圖定位[1022:55837] 您的當(dāng)前位置:經(jīng)度:-116.506400,緯度:39.285834,海拔:0.000000,航向:-1.000000,速度:-1.000000


根據(jù)經(jīng)緯度計(jì)算兩地的距離

ViewController.m

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()
@property (nonatomic,strong)CLLocationManager *locationManager;
@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //創(chuàng)建位置管理器
    CLLocationManager *locationManager=[[CLLocationManager alloc]init];
    self.locationManager=locationManager;
    
    //判斷當(dāng)前設(shè)備版本是否大于或等于8.0
    if ([UIDevice currentDevice].systemVersion.floatValue >=8.0) {
        //持續(xù)授權(quán)
        //[locationManager requestAlwaysAuthorization];
        //使用期間授權(quán)
        [locationManager requestWhenInUseAuthorization];
    }
    //iOS 9.0以后蘋果提供的新屬性
    if ([UIDevice currentDevice].systemVersion.floatValue >9.0) {
        //是否允許后臺(tái)定位
        locationManager.allowsBackgroundLocationUpdates=YES;
    }
    
    //開始定位
    [locationManager startUpdatingLocation];
    //比較兩點(diǎn)距離
    [self compareDistance];
}

//比較兩地之間距離(直線距離)
- (void)compareDistance{
    //北京 (116.3,39.9)
    CLLocation *location1=[[CLLocation alloc]initWithLatitude:39.9 longitude:116.3];
    //鄭州 (113.42,34.44)
    CLLocation *location2=[[CLLocation alloc]initWithLatitude:34.44 longitude:113.42];
    //比較北京距離鄭州的距離
    CLLocationDistance locationDistance=[location1 distanceFromLocation:location2];
    //單位是m/s 所以這里需要除以1000
    NSLog(@"北京距離鄭州的距離為:%f",locationDistance/1000);

}

運(yùn)行結(jié)果:

2015-11-29 16:36:44.742 測(cè)量?jī)牲c(diǎn)間距離[1500:125741] 北京距離鄭州的距離為:657.622676

地理編碼與反地理編碼

  • 地理編碼:根據(jù)地址獲得相應(yīng)的經(jīng)緯度以及詳細(xì)信息
  • 反地理編碼:根據(jù)經(jīng)緯度獲取詳細(xì)的地址信息(比如:省市、街區(qū)、樓層、門牌等信息)

地理編碼與反地理編碼用到得兩個(gè)方法

//地理編碼
- (void)geocodeAddressString:(NSString *)addressString completionHandler:(CLGeocodeCompletionHandler)completionHandler;

//反地理編碼
 - (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;

地理編碼的使用

ViewController.m

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()
//地址
@property (weak, nonatomic) IBOutlet UITextField *addressTextField;
//經(jīng)度
@property (weak, nonatomic) IBOutlet UITextField *longitudeTextField;
//緯度
@property (weak, nonatomic) IBOutlet UITextField *latitudeTextField;
//詳細(xì)地址
@property (weak, nonatomic) IBOutlet UITextView *textView;

@end

@implementation ViewController

//地理編碼
- (IBAction)genocoder:(id)sender {
    //創(chuàng)建編碼對(duì)象
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    //判斷是否為空
    if (self.addressTextField.text.length ==0) {
        return;
    }
    [geocoder geocodeAddressString:self.addressTextField.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error!=nil || placemarks.count==0) {
            return ;
        }
        //創(chuàng)建placemark對(duì)象
        CLPlacemark *placemark=[placemarks firstObject];
        //賦值經(jīng)度
        self.longitudeTextField.text =[NSString stringWithFormat:@"%f",placemark.location.coordinate.longitude];
        //賦值緯度
        self.latitudeTextField.text=[NSString stringWithFormat:@"%f",placemark.location.coordinate.latitude];
        //賦值詳細(xì)地址
        self.textView.text=placemark.name;
    }];
    
}

反地理編碼的使用

AntiEncoderController.m

#import "AntiEncoderController.h"
#import <CoreLocation/CoreLocation.h>

@interface AntiEncoderController ()
//經(jīng)度
@property (weak, nonatomic) IBOutlet UITextField *longitudeTextField;
//緯度
@property (weak, nonatomic) IBOutlet UITextField *latitudeTextField;
//詳細(xì)地址
@property (weak, nonatomic) IBOutlet UITextView *textView;
@end

@implementation AntiEncoderController

//反地理編碼
- (IBAction)AntiEncoder:(id)sender {
    //創(chuàng)建地理編碼對(duì)象
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    //創(chuàng)建位置
    CLLocation *location=[[CLLocation alloc]initWithLatitude:[self.latitudeTextField.text floatValue] longitude:[self.longitudeTextField.text floatValue]];
    
    //反地理編碼
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //判斷是否有錯(cuò)誤或者placemarks是否為空
        if (error !=nil || placemarks.count==0) {
            NSLog(@"%@",error);
            return ;
        }
        for (CLPlacemark *placemark in placemarks) {
            //賦值詳細(xì)地址
            self.textView.text=placemark.name;
        }
        
    }];
    
}


mapView的使用

ViewController.m

#import "ViewController.h"
#import <MapKit/MapKit.h>

@interface ViewController ()<MKMapViewDelegate>
//mapView
@property (weak, nonatomic) IBOutlet MKMapView *mapView;

@property (nonatomic,strong)CLLocationManager *locationManager;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CLLocationManager *locationManager=[[CLLocationManager alloc]init];
    self.locationManager=locationManager;
    
    //請(qǐng)求授權(quán)
    [locationManager requestWhenInUseAuthorization];

    /*
     MKUserTrackingModeNone  不進(jìn)行用戶位置跟蹤
     MKUserTrackingModeFollow  跟蹤用戶的位置變化
     MKUserTrackingModeFollowWithHeading  跟蹤用戶位置和方向變化
     */
    //設(shè)置用戶的跟蹤模式
    self.mapView.userTrackingMode=MKUserTrackingModeFollow;
    /*
     MKMapTypeStandard  標(biāo)準(zhǔn)地圖
     MKMapTypeSatellite    衛(wèi)星地圖
     MKMapTypeHybrid      鳥瞰地圖
     MKMapTypeSatelliteFlyover
     MKMapTypeHybridFlyover
     */
    self.mapView.mapType=MKMapTypeStandard;
    //實(shí)時(shí)顯示交通路況
    self.mapView.showsTraffic=YES;
    //設(shè)置代理
    self.mapView.delegate=self;
    
}

//跟蹤到用戶位置時(shí)會(huì)調(diào)用該方法
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    //創(chuàng)建編碼對(duì)象
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    //反地理編碼
    [geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error!=nil || placemarks.count==0) {
            return ;
        }
        //獲取地標(biāo)
        CLPlacemark *placemark=[placemarks firstObject];
        //設(shè)置標(biāo)題
        userLocation.title=placemark.locality;
        //設(shè)置子標(biāo)題
        userLocation.subtitle=placemark.name;
    }];
    
}

//回到當(dāng)前位置
- (IBAction)backCurrentLocation:(id)sender {
    
    MKCoordinateSpan span=MKCoordinateSpanMake(0.021251, 0.016093);
    
    [self.mapView setRegion:MKCoordinateRegionMake(self.mapView.userLocation.coordinate, span) animated:YES];
}

//當(dāng)區(qū)域改變時(shí)調(diào)用
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    //獲取系統(tǒng)默認(rèn)定位的經(jīng)緯度跨度
    NSLog(@"維度跨度:%f,經(jīng)度跨度:%f",mapView.region.span.latitudeDelta,mapView.region.span.longitudeDelta);
}

//縮小地圖
- (IBAction)minMapView:(id)sender {
   
    //獲取維度跨度并放大一倍
    CGFloat latitudeDelta = self.mapView.region.span.latitudeDelta * 2;
    //獲取經(jīng)度跨度并放大一倍
    CGFloat longitudeDelta = self.mapView.region.span.longitudeDelta * 2;
    //經(jīng)緯度跨度
    MKCoordinateSpan span = MKCoordinateSpanMake(latitudeDelta, longitudeDelta);
    //設(shè)置當(dāng)前區(qū)域
    MKCoordinateRegion region = MKCoordinateRegionMake(self.mapView.centerCoordinate, span);
    
    [self.mapView setRegion:region animated:YES];
}

//放大地圖
- (IBAction)maxMapView:(id)sender {
    
    //獲取維度跨度并縮小一倍
    CGFloat latitudeDelta = self.mapView.region.span.latitudeDelta * 0.5;
    //獲取經(jīng)度跨度并縮小一倍
    CGFloat longitudeDelta = self.mapView.region.span.longitudeDelta * 0.5;
    //經(jīng)緯度跨度
    MKCoordinateSpan span = MKCoordinateSpanMake(latitudeDelta, longitudeDelta);
    //設(shè)置當(dāng)前區(qū)域
    MKCoordinateRegion region = MKCoordinateRegionMake(self.mapView.centerCoordinate, span);
    
    [self.mapView setRegion:region animated:YES];

}

向mapView上添加大頭針

  • 只要我們的NSObject實(shí)現(xiàn)MKAnnotation協(xié)議,就可以作為一個(gè)大頭針供我們使用,通常我們?cè)谖覀兊念愔幸貙憛f(xié)議中coordinate(標(biāo)記位置)、title(標(biāo)題)、subtitle(子標(biāo)題)三個(gè)屬性,然后在程序中創(chuàng)建大頭針對(duì)象并調(diào)用addAnnotation:方法添加大頭針即可

ZKAnnotation.h

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
//遵循協(xié)議
@interface ZKAnnotation : NSObject<MKAnnotation>
//經(jīng)緯度
@property (nonatomic)CLLocationCoordinate2D coordinate;
//父標(biāo)題
@property (nonatomic,copy)NSString *title;
//子標(biāo)題
@property (nonatomic,copy)NSString *subtitle;

@end

ViewController.h

#import "ViewController.h"
#import <MapKit/MapKit.h>
#import "ZKAnnotation.h"

@interface ViewController ()<MKMapViewDelegate>
//mapView視圖
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    ZKAnnotation *annotation=[[ZKAnnotation alloc]init];
    annotation.coordinate=CLLocationCoordinate2DMake(39.9, 116);
    annotation.title=@"我是父標(biāo)題";
    annotation.subtitle=@"我是子標(biāo)題";
    
    self.mapView.delegate=self;
    //添加大頭針到北京
    [self.mapView addAnnotation:annotation];
}
//當(dāng)點(diǎn)擊屏幕的時(shí)候調(diào)用
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    //獲取用戶點(diǎn)擊的位置
    CGPoint point=[[touches anyObject]locationInView:self.mapView];
    //將具體的位置轉(zhuǎn)換為經(jīng)緯度
    CLLocationCoordinate2D coordinate=[self.mapView convertPoint:point toCoordinateFromView:self.mapView];

    //添加大頭針
    ZKAnnotation *annotation=[[ZKAnnotation alloc]init];
    annotation.coordinate=coordinate;
    
    //反地理編碼
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    CLLocation *location=[[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error==nil && placemarks.count==0) {
            NSLog(@"錯(cuò)誤信息:%@",error);
            return ;
        }
        //獲取地標(biāo)信息
        CLPlacemark *placemark=[placemarks firstObject];
        //獲取父標(biāo)題名稱
        annotation.title=placemark.locality;
        //獲取子標(biāo)題名稱
        annotation.subtitle=placemark.name;

        //添加大頭針到地圖
        [self.mapView addAnnotation:annotation];
    }];
    
}


效果如下

mapView.gif

動(dòng)態(tài)添加大頭針到地圖

ZKAnnotation.h

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface ZKAnnotation : NSObject<MKAnnotation>
//經(jīng)緯度
@property (nonatomic) CLLocationCoordinate2D coordinate;
//標(biāo)題
@property (nonatomic, copy) NSString *title;
//子標(biāo)題
@property (nonatomic, copy) NSString *subtitle;
@end

ViewController.m

#import "ViewController.h"
#import <MapKit/MapKit.h>
#import "ZKAnnotation.h"

@interface ViewController ()<MKMapViewDelegate>
//創(chuàng)建管理者
@property (nonatomic,strong)CLLocationManager *locationManager;
//mapView
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 1.創(chuàng)建大頭針模型
    ZKAnnotation *annotation = [[ZKAnnotation alloc] init];
    annotation.coordinate = CLLocationCoordinate2DMake(39.9, 116);
    annotation.title = @"北京";
    annotation.subtitle = @"默認(rèn)顯示的為首都北京";
    
    //添加第一個(gè)大頭針模型
    [self.mapView addAnnotation:annotation];
    //設(shè)置代理
    self.mapView.delegate = self;
    
    //請(qǐng)求授權(quán)
    self.locationManager = [[CLLocationManager alloc] init];
    [self.locationManager requestWhenInUseAuthorization];
    
    //設(shè)置用戶跟蹤模式
    //self.mapView.userTrackingMode = MKUserTrackingModeFollow;
}

//點(diǎn)擊屏幕的時(shí)候調(diào)用
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //獲取用戶點(diǎn)擊的位置
    CGPoint point=[[touches anyObject]locationInView:self.mapView];
    //將具體的位置轉(zhuǎn)換為經(jīng)緯度
    CLLocationCoordinate2D coordinate=[self.mapView convertPoint:point toCoordinateFromView:self.mapView];
    
    //添加大頭針
    ZKAnnotation *annotation=[[ZKAnnotation alloc]init];
    annotation.coordinate=coordinate;
    
    //反地理編碼
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    CLLocation *location=[[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error==nil && placemarks.count==0) {
            NSLog(@"錯(cuò)誤信息:%@",error);
            return ;
        }
        //獲取地標(biāo)信息
        CLPlacemark *placemark=[placemarks firstObject];
        //獲取父標(biāo)題名稱
        annotation.title=placemark.locality;
        //獲取子標(biāo)題名稱
        annotation.subtitle=placemark.name;
        
        //添加大頭針到地圖
        [self.mapView addAnnotation:annotation];
    }];

}

//創(chuàng)建大頭針時(shí)調(diào)用
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    //如果返回空,代表大頭針樣式交由系統(tǒng)去管理
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    static NSString *ID = @"annotation";
    // MKAnnotationView 默認(rèn)沒有界面  可以顯示圖片
    // MKPinAnnotationView有界面      默認(rèn)不能顯示圖片
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:ID];
    if (annotationView == nil) {
        annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ID];
        //設(shè)置大頭針顏色
        annotationView.pinTintColor = [UIColor redColor];
        //設(shè)置為動(dòng)畫掉落的效果
        annotationView.animatesDrop = YES;
        //顯示詳情
        annotationView.canShowCallout = YES;
    }
    return annotationView;
}
@end

效果如下

動(dòng)態(tài)添加大頭針.gif

導(dǎo)航

除了可以使用MapKit框架進(jìn)行地圖開發(fā),對(duì)地圖有精確的控制和自定義之外,如果對(duì)于應(yīng)用沒有特殊要求的話選用蘋果自帶的地圖應(yīng)用也是一個(gè)不錯(cuò)的選擇。想使用蘋果自帶的地圖,我們需要用到MapKit中的MKMapItem類,這個(gè)類中有如下兩個(gè)方法:

  • openInMapsWithLaunchOptions:用于在地圖上標(biāo)注一個(gè)位置
  • openMapsWithItems: launchOptions:除了可以標(biāo)注多個(gè)位置外還可以進(jìn)行多個(gè)位置之間的駕駛導(dǎo)航
MKLaunchOptionsDirectionsModeKey :路線模式,常量
  • MKLaunchOptionsDirectionsModeDriving 駕車模式
  • MKLaunchOptionsDirectionsModeWalking 步行模式
MKLaunchOptionsMapTypeKey:地圖類型,枚舉
  • MKMapTypeStandard :標(biāo)準(zhǔn)模式
  • MKMapTypeSatellite :衛(wèi)星模式
  • MKMapTypeHybrid :混合模式
MKLaunchOptionsMapCenterKey:中心點(diǎn)坐標(biāo),CLLocationCoordinate2D類型
MKLaunchOptionsMapSpanKey:地圖顯示跨度,MKCoordinateSpan 類型
MKLaunchOptionsShowsTrafficKey:是否 顯示交通狀況,布爾型
MKLaunchOptionsCameraKey:3D地圖效果,MKMapCamera類型

注意:此屬性從iOS7及以后可用,前面的屬性從iOS6開始可用

ViewController.m

#import "ViewController.h"
#import <MapKit/MapKit.h>

@interface ViewController ()
//地址
@property (weak, nonatomic) IBOutlet UITextField *addressText;

@end

@implementation ViewController

//開始導(dǎo)航
- (IBAction)begin:(id)sender {
    
    //創(chuàng)建CLGeocoder對(duì)象
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:self.addressText.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //獲取目的地地理坐標(biāo)
        CLPlacemark *placemark = [placemarks lastObject];
        //Mapkit框架下的地標(biāo)
        MKPlacemark *mkPlacemark = [[MKPlacemark alloc] initWithPlacemark:placemark];
        //目的地的item
        MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:mkPlacemark];
        MKMapItem *currentmapItem = [MKMapItem mapItemForCurrentLocation];
        NSMutableDictionary *options = [NSMutableDictionary dictionary];
        //MKLaunchOptionsDirectionsModeDriving:導(dǎo)航類型設(shè)置為駕車模式
        options[MKLaunchOptionsDirectionsModeKey] = MKLaunchOptionsDirectionsModeDriving;
        //設(shè)置地圖顯示類型為衛(wèi)星模式
        options[MKLaunchOptionsMapTypeKey] = @(MKMapTypeHybrid);
        options[MKLaunchOptionsShowsTrafficKey] =@(YES);
        //打開蘋果地圖應(yīng)用
        [MKMapItem openMapsWithItems:@[currentmapItem,mapItem] launchOptions:options];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

效果如下

導(dǎo)航.gif

以上Demo下載路徑:https://github.com/chengaojian

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容