在app中有许多场景需要用到导航,比如 我给你发了一个地理位置,你可以打开这个位置然后通过位置导航找到我.
导航可以通过内嵌三方SDK实现也可以通过跳转三方app实现,后者相对前者来说相对简单而且也能有效的减小app体积.下面就为大家介绍下后者实现.
// 代码如下 这里只添加了三种地图 (苹果官方地图,高德,百度),如有其它需要可以自己添加,如果没有安装高德或者百度地图 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的代理方法
- (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 = 目的地经纬度
// 只有调用百度地图才需要当前的经纬度
_myLocation = 当前经纬度
具体 这些URL以及参数的设置都可以在官方文档查看
需要注意的是 iOS9.0以上的系统需要在info.plist文件设置白名单才能调起三方地图
白名单设置
设置URLScheme
info->URLTypes 添加urlScheme
如此便可以轻松的在app中调用三方地图进行导航了!