iOS實現應用外自帶地圖、高德地圖、百度地圖導航

歡迎訪問我的博客muhlenXi,該文章出自我的博客。

版權聲明:本文為muhlenXi原創文章,轉載請注明出處,未經允許不得轉載.

導語:

   在地圖類應用開發中,我們經常有導航這個功能需求。根據導航方式可以分為應用內導航和應用外導航,其中應用內導航指的是使用第三方提供的地圖SDK(高德、百度等)將導航嵌入到我們開發的APP內部。應用外導航指的是以URL Scheme 跳轉的方式,跳轉到對應的地圖APP中,使用對方的導航功能。

本次開發的需求是,實現應用外導航。通過選項列表(UIAlertControllerUIActionSheet)的方式提供用戶選擇,當用戶既安裝了高德地圖和百度地圖時,則彈出如下圖所示的選項列表。否則用戶安裝了哪個地圖,就增加哪個地圖的選擇項。

選項列表圖

環境的配置

在iOS 9 下涉及到平臺客戶端跳轉,系統會自動到項目info.plist下檢測是否設置平臺Scheme,對于需要配置的平臺,如果沒有配置,將無法正常跳轉平臺客戶端,因此需要配置Scheme名單。本文我們需要添加百度地圖和高德地圖的scheme白名單。

具體方法:在項目的info.plist中添加LSApplicationQueriesSchemes字段,類型是Array,然后添加兩個Item。

如圖:

配置Scheme名單

根據系統的版本號來初始化對應選項列表

我們需要一個屬性來記錄導航目標的終點坐標

@property (nonatomic,assign) CLLocationCoordinate2D coordinate;  //!< 要導航的坐標

viewDidLoad中初始化該坐標值。

    //導航到深圳火車站
    self.coordinate = CLLocationCoordinate2DMake(22.53183, 114.117206);

我們再定義一個判斷系統版本是否大于等于8.0的一個宏定義

//系統版本號是否大于8.0
#define IS_SystemVersionGreaterThanEight  ([UIDevice currentDevice].systemVersion.doubleValue >= 8.0)

在低于8.0的系統版本中使用UIAlertController會崩潰,所以我們要根據系統版本號來選擇合適的選項列表。

在導航按鈕的事件響應方法中,我們添加如下代碼:

     //系統版本高于8.0,使用UIAlertController
    if (IS_SystemVersionGreaterThanEight) {
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"導航到設備" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        //自帶地圖
        [alertController addAction:[UIAlertAction actionWithTitle:@"自帶地圖" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSLog(@"alertController -- 自帶地圖");
            
            //使用自帶地圖導航
            MKMapItem *currentLocation =[MKMapItem mapItemForCurrentLocation];
            
            MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:self.coordinate addressDictionary:nil]];
            
            [MKMapItem openMapsWithItems:@[currentLocation,toLocation] launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
    
            
        }]];
        
        //判斷是否安裝了高德地圖,如果安裝了高德地圖,則使用高德地圖導航
        if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
            
            [alertController addAction:[UIAlertAction actionWithTitle:@"高德地圖" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
             NSLog(@"alertController -- 高德地圖");
             NSString *urlsting =[[NSString stringWithFormat:@"iosamap://navi?sourceApplication= &backScheme= &lat=%f&lon=%f&dev=0&style=2",self.coordinate.latitude,self.coordinate.longitude]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [[UIApplication  sharedApplication]openURL:[NSURL URLWithString:urlsting]];
                
            }]];
        }
        
        //判斷是否安裝了百度地圖,如果安裝了百度地圖,則使用百度地圖導航
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
            [alertController addAction:[UIAlertAction actionWithTitle:@"百度地圖" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
               
             NSLog(@"alertController -- 百度地圖");
             NSString *urlsting =[[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",self.coordinate.latitude,self.coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];
                
            }]];
        }
        
        //添加取消選項
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            [alertController dismissViewControllerAnimated:YES completion:nil];
            
        }]];
        
        //顯示alertController
        [self presentViewController:alertController animated:YES completion:nil];

    }
    else {  //系統版本低于8.0,則使用UIActionSheet
        
        UIActionSheet * actionsheet = [[UIActionSheet alloc] initWithTitle:@"導航到設備" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"自帶地圖", nil];
        
        //如果安裝高德地圖,則添加高德地圖選項
        if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
            
            [actionsheet addButtonWithTitle:@"高德地圖"];
         
        }
        
        //如果安裝百度地圖,則添加百度地圖選項
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
            
            [actionsheet addButtonWithTitle:@"百度地圖"];
        }
    
        [actionsheet showInView:self.view];
       
        
    }

實現UIActionSheetDelegate 代理方法

當使用UIActionSheet時,需要設置Delegateself,并且遵循UIActionSheetDelegate協議,實現相應代理方法。

當點擊取消選項時,會觸發該代理方法

#pragma mark - UIActionSheetDelegate

- (void)actionSheetCancel:(UIActionSheet *)actionSheet
{
    NSLog(@"ActionSheet - 取消了");
    [actionSheet removeFromSuperview];
}

當點擊其他選項是,則會觸發下面的代理方法

使用自帶地圖導航時,需要用到MKMapItem,我們需要導入頭文件#import <MapKit/MapKit.h>

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    NSLog(@"numberOfButtons == %ld",actionSheet.numberOfButtons);
     NSLog(@"buttonIndex == %ld",buttonIndex);
    
    if (buttonIndex == 0) {
        
        NSLog(@"自帶地圖觸發了");
        
        MKMapItem *currentLocation =[MKMapItem mapItemForCurrentLocation];
        
        MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:self.coordinate addressDictionary:nil]];
        
        [MKMapItem openMapsWithItems:@[currentLocation,toLocation] launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
            MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];

    }
    //既安裝了高德地圖,又安裝了百度地圖
    if (actionSheet.numberOfButtons == 4) {
        
        if (buttonIndex == 2) {
            
            NSLog(@"高德地圖觸發了");
            
            NSString *urlsting =[[NSString stringWithFormat:@"iosamap://navi?sourceApplication= &backScheme= &lat=%f&lon=%f&dev=0&style=2",self.coordinate.latitude,self.coordinate.longitude]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [[UIApplication  sharedApplication]openURL:[NSURL URLWithString:urlsting]];
        }
        if (buttonIndex == 3) {
            
            NSLog(@"百度地圖觸發了");
            NSString *urlsting =[[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",self.coordinate.latitude,self.coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];
        }
 
    }
    //安裝了高德地圖或安裝了百度地圖
    if (actionSheet.numberOfButtons == 3) {
        
        if (buttonIndex == 2) {
            
            if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
                
                NSLog(@"只安裝的高德地圖觸發了");
                NSString *urlsting =[[NSString stringWithFormat:@"iosamap://navi?sourceApplication= &backScheme= &lat=%f&lon=%f&dev=0&style=2",self.coordinate.latitude,self.coordinate.longitude]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [[UIApplication  sharedApplication]openURL:[NSURL URLWithString:urlsting]];
               
            }
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
                 NSLog(@"只安裝的百度地圖觸發了");
                NSString *urlsting =[[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",self.coordinate.latitude,self.coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];
            }

           
        }
        
    }
    
}

知識點補充

【1】使用canOpenURL方法來檢測該手機是否安裝相應APP

該方法會返回一個BOOL值,當為YES時,表明已安裝該APP

[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]

常用的4個地圖的 URL Scheme:

  • 1、蘋果自帶地圖(不需要檢測,所以不需要URL Scheme)
  • 2、百度地圖 baidumap://
  • 3、高德地圖 iosamap://
  • 4、谷歌地圖 comgooglemaps://

點擊這里查看更多常用的URL Scheme

對URL Scheme不了解的點這里

如何自定義URL Scheme點這里

【2】wgs84gcj-02,bd-09是什么?

wgs84是國際標準,從GPS設備中取出的原始數據就是這個標準的數據,iOS的SDK中用到的坐標系統也是國際標準的坐標系統WGS-84;

gcj-02是中國標準,行貨GPS設備取出的原始數據是該標準的數據,根據規定,國內出版的各種地圖系統,必須至少采用gcj-02對地理位置進行首次加密。網絡上也稱之為火星坐標。

bd-09是百度標準,百度SDK使用的就是這個標準。

如何進行轉換點這里

運行結果圖示

以下是選擇了不同的選項對應的結果圖。

自帶地圖導航。

自帶地圖導航

高德地圖導航。

高德地圖導航

百度地圖導航。

百度地圖導航

感謝閱讀,有什么意見可以給我留言!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,546評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,570評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,505評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,017評論 1 313
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,786評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,219評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,287評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,438評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,971評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,796評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,995評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,540評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,230評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,918評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,697評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內容