最近接到需求,做跳转到App外调用地图进行导航。一般在大陆,手机上常用地图就是百度地图,高德地图,和苹果自带的地图。下面就按照介绍下跳到三个地图App内的方法。
*苹果自带地图,此时需要传入目的地,交通方式。
self.lat = 22.5369144502;
self.lon = 113.9226940117;
self.destination = @"南山文体中心";
//终点坐标
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(self.lat, self.lon);
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择地图" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"用iPhone自带地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//当前位置
MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil]];
//传入目的地,会显示在苹果自带地图上面目的地一栏
toLocation.name = self.destination;
//导航方式选择walking
[MKMapItem openMapsWithItems:@[currentLocation, toLocation]
launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeWalking,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
}];
[alert addAction:action];
*百度地图,传入目标位置以name:传入经纬度,交通方式。如需要跳到导航,则将map改为navi。
if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]])
{
UIAlertAction *action = [UIAlertAction actionWithTitle:@"用百度地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name:%@&mode=walking&coord_type=gcj02",coordinate.latitude, coordinate.longitude,self.destination] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",urlString);
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}];
[alert addAction:action];
}
*高德地图,闯入经纬度和目的地,还有App名称。sourceApplication:App名称,dlat:经度,dlon:纬度,dname:目的地。t:交通方式。path:表示路线规划,改为navi为直接语音导航。
if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]])
{
UIAlertAction *action = [UIAlertAction actionWithTitle:@"用高德地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSString *urlString = [[NSString stringWithFormat:@"iosamap://path?sourceApplication=%@&sid=BGVIS1&did=BGVIS2&dlat=%f&dlon=%f&dname=%@&dev=0&t=2",@"刷哪儿",coordinate.latitude,coordinate.longitude,self.destination] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",urlString);
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}];
[alert addAction:action];
}
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:cancelAction];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:^{
}];