在app中有許多場景須要用到導航,好比 我給你發了一個地理位置,你能夠打開這個位置而後經過位置導航找到我.ios
導航能夠經過內嵌三方SDK實現也能夠經過跳轉三方app實現,後者相對前者來講相對簡單並且也能有效的減少app體積.下面就爲你們介紹下後者實現.git
// 代碼以下 這裏只添加了三種地圖 (蘋果官方地圖,高德,百度),若有其它須要能夠本身添加,若是沒有安裝高德或者百度地圖 sheet的titles裏面是不會顯示的 UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"選擇地圖" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil, nil]; if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com/"]]) { [sheet addButtonWithTitle:@"蘋果地圖"]; } if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) { [sheet addButtonWithTitle:@"百度地圖"]; } if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) { [sheet addButtonWithTitle:@"高德地圖"]; } [sheet showInView:self.view];
下面實現actionSheet的代理方法app
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex]; if ([title isEqualToString:@"蘋果地圖"]) { MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation]; MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:_currentLocationCoordinate addressDictionary:nil]]; // 目的地名字 toLocation.name = self.addressString; [MKMapItem openMapsWithItems:@[currentLocation, toLocation] launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}]; } else if ([title isEqualToString:@"高德地圖"]) { NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",self.appName,self.urlScheme, _toLocationCoordinate.latitude, _toLocationCoordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]]; } else if ([title isEqualToString:@"百度地圖"]) { NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin=%f,%f&destination=latlng:%f,%f|name:%@&mode=driving&src=dangdang://&coord_type=gcj02", _myLocation.latitude,_myLocation.longitude, _toLocationCoordinate.latitude, _toLocationCoordinate.longitude, self.addressString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%@",urlString); [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]]; } }
// 通用參數
self.appName = app名稱 self.urlScheme = appUrlScheme _toLocationCoordinate = 目的地經緯度url
// 只有調用百度地圖才須要當前的經緯度
_myLocation = 當前經緯度 spa
具體 這些URL以及參數的設置均可以在官方文檔查看
須要注意的是 iOS9.0以上的系統須要在info.plist文件設置白名單才能調起三方地圖代理
白名單設置code
設置URLSchemeorm
info->URLTypes 添加urlScheme文檔
如此即可以輕鬆的在app中調用三方地圖進行導航了!string