ios各种地图的跳转并导航

本文介绍了一个集成多种地图应用(如苹果地图、百度地图等)进行导航的iOS应用案例。通过判断设备是否安装了对应的地图应用并调用相应应用进行导航,为用户提供多样化的导航选择。
部署运行你感兴趣的模型镜像

#import "XTMapKitViewController.h"

@interface XTMapKitViewController (){
    MKMapView *_mapView;
    CLLocationCoordinate2D _coordinate;
    
    UIActionSheet *_actionSheet;
    NSMutableArray *_mapsUrlArray;
}

@end

@implementation XTMapKitViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //适配ios7
    [self FitToiOS7];
    //创建NAV
    [self creatNav];
    [self creatNavBackBarButtonItem];
    self.titleLabel.text=@"地图";
    self.view.backgroundColor=[XTColorToImage colorWithHexString:@"#F0F0F3"];
    
    [self creatMapViews];
    
}

-(void)creatMapViews{
    
    _mapView=[[MKMapView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-117)];
    _mapView.delegate=self;
    
    _mapView.showsUserLocation=YES;
    [self.view addSubview:_mapView];
    
    UIView * backView=[[UIView alloc] initWithFrame:CGRectMake(0, XTViewHeight(_mapView), 320, 53)];
    backView.backgroundColor=[XTColorToImage colorWithHexString:@"#2F3737"];
    [self.view addSubview:backView];
    
    UIButton * mapButton=[UIButton buttonWithType:UIButtonTypeCustom];
    mapButton.frame=CGRectMake(0, 0, 160, 44);
    [mapButton setTitle:@"查看其它地图" forState:UIControlStateNormal];
    mapButton.titleLabel.font=[UIFont systemFontOfSize:12.0f];
    [mapButton setImageEdgeInsets:UIEdgeInsetsMake(0, 60, 0, 40)];
    [mapButton setTitleEdgeInsets:UIEdgeInsetsMake(45, 15, 0, 35)];//4个参数是上边界,左边界,下边界,右边界
    [mapButton setImage:[UIImage imageNamed:@"map_other"] forState:UIControlStateNormal];
    [mapButton addTarget:self action:@selector(openOtherMap) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:mapButton];
    
    UIButton * errorButton=[UIButton buttonWithType:UIButtonTypeCustom];
    errorButton.frame=CGRectMake(160, 0, 160, 44);
    errorButton.titleLabel.font=[UIFont systemFontOfSize:12.0f];
    [errorButton setTitle:@"报错" forState:UIControlStateNormal];
    [errorButton setImageEdgeInsets:UIEdgeInsetsMake(0, 60, 0, 60)];
    [errorButton setTitleEdgeInsets:UIEdgeInsetsMake(45, 15, 0, 50)];//4个参数是上边界,左边界,下边界,右边界
    [errorButton setImage:[UIImage imageNamed:@"map_error"] forState:UIControlStateNormal];
    [errorButton addTarget:self action:@selector(SendError) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:errorButton];
}

-(void)SendError{
    
    
    
}

-(void)openOtherMap{
    
    _actionSheet= [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                      cancelButtonTitle:nil
                                 destructiveButtonTitle:nil
                                      otherButtonTitles:nil];
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    NSMutableArray *mapsArray=[[NSMutableArray alloc] initWithCapacity:0];
    _mapsUrlArray=[[NSMutableArray alloc] init];
    
    NSURL * apple_App = [NSURL URLWithString:@"http://maps.apple.com/"];
    if ([[UIApplication sharedApplication] canOpenURL:apple_App]) {
        [mapsArray addObject:@"使用苹果自带地图导航"];
        
        NSString *str=[NSString stringWithFormat:@"http://maps.apple.com/?daddr=%f,%f&saddr=%f,%f",delegate.y_axis,delegate.x_axis,self.shop_y,self.shop_x];
        [_mapsUrlArray addObject:str];
    }
    NSURL * baidu_App = [NSURL URLWithString:@"baidumap://"];
                                              
    if ([[UIApplication sharedApplication] canOpenURL:baidu_App]) {
        [mapsArray addObject:@"使用百度地图导航"];
        
        CLLocation * myLocation=[[CLLocation alloc]initWithLatitude:delegate.y_axis longitude:delegate.x_axis];
        
        myLocation=[myLocation locationBaiduFromMars];
        
        CLLocationCoordinate2D currentLocation=[myLocation coordinate];//当前经纬度
        float x_axis=currentLocation.longitude;
        float y_axis=currentLocation.latitude;
        
        CLLocation * myLocationTwo=[[CLLocation alloc]initWithLatitude:self.shop_y longitude:self.shop_x];
        
        myLocationTwo=[myLocationTwo locationBaiduFromMars];
        
        CLLocationCoordinate2D currentLocationTwo=[myLocationTwo coordinate];//当前经纬度
        float x_a=currentLocationTwo.longitude;
        float y_a=currentLocationTwo.latitude;
        
        NSString *str=[NSString stringWithFormat:@"baidumap://map/direction?origin=%f,%f&destination=%f,%f&mode=walking&src=companyName|appName",y_axis,x_axis,y_a,x_a];
        
        
        [_mapsUrlArray addObject:str];
    }
    NSURL * gaode_App = [NSURL URLWithString:@"iosamap://"];
    if ([[UIApplication sharedApplication] canOpenURL:gaode_App]) {
        [mapsArray addObject:@"使用高德地图导航"];
        
        NSString *str=[NSString stringWithFormat:@"iosamap://path?sourceApplication=applicationName&backScheme=applicationScheme&slat=%f&slon=%f&sname=我&dlat=%f&dlon=%f&dname=%@&dev=0&m=0&t=1",delegate.y_axis,delegate.x_axis,self.shop_y,self.shop_x,self.shopName];
        
        
        [_mapsUrlArray addObject:str];
    }
    NSURL * google_App = [NSURL URLWithString:@"comgooglemaps://"];
    if ([[UIApplication sharedApplication] canOpenURL:google_App]) {
        [mapsArray addObject:@"使用Google Maps导航"];
        
        NSString *str=[NSString stringWithFormat:@"comgooglemaps://?saddr=%f,%f&daddr=%f,%f&directionsmode=walking",delegate.y_axis,delegate.x_axis,self.shop_y,self.shop_x];
        [_mapsUrlArray addObject:str];
    }
    
    for (int x=0; x<mapsArray.count; x++) {
        [_actionSheet addButtonWithTitle:[mapsArray objectAtIndex:x]];
        
    }
    
    [_actionSheet addButtonWithTitle:@"取消"];
    // 将取消按钮的index设置成我们刚添加的那个按钮,这样在delegate中就可以知道是那个按钮
    // NB - 这会导致该按钮显示时有黑色背景
    _actionSheet.cancelButtonIndex = _actionSheet.numberOfButtons-1;
    [_actionSheet showInView:self.view.window];
}

#pragma --mark-- actionsheetdelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex)
    {
        return;
    }
    if (buttonIndex==0) {
        CLLocationCoordinate2D to;
        
        to.latitude = self.shop_y;
        to.longitude = self.shop_x;
        MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        
        MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:to addressDictionary:nil]];
        
        
        toLocation.name =self.shopName;
        [MKMapItem openMapsWithItems:[NSArray arrayWithObjects:currentLocation, toLocation, nil]
                       launchOptions:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:MKLaunchOptionsDirectionsModeWalking, [NSNumber numberWithBool:YES], nil]
                                      
                                      
                                                                 forKeys:[NSArray arrayWithObjects:MKLaunchOptionsDirectionsModeKey, MKLaunchOptionsShowsTrafficKey, nil]]];
    }
    else{
        NSString *str=[_mapsUrlArray objectAtIndex:buttonIndex];
        str=[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL * myURL_APP_A =[[NSURL alloc] initWithString:str];
        NSLog(@"%@",myURL_APP_A);
        if ([[UIApplication sharedApplication] canOpenURL:myURL_APP_A]) {
            
            [[UIApplication sharedApplication] openURL:myURL_APP_A];
        }
    }
    
}


#pragma mark - MKMapViewDelegate

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView
            rendererForOverlay:(id<MKOverlay>)overlay
{
    MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
    renderer.lineWidth = 5.0;
    renderer.strokeColor = [UIColor purpleColor];
    return renderer;
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    _coordinate.latitude = userLocation.location.coordinate.latitude;
    _coordinate.longitude = userLocation.location.coordinate.longitude;
    
    [self setMapRegionWithCoordinate:_coordinate];
}

- (void)setMapRegionWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    MKCoordinateRegion region;
    
    region = MKCoordinateRegionMake(coordinate, MKCoordinateSpanMake(.1, .1));
    MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:region];
    [_mapView setRegion:adjustedRegion animated:YES];
}


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

@end

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

### 微信小程序跳转百度地图启动导航功能的实现 要在微信小程序中实现点击后跳转至百度地图启动导航功能,可以通过以下方式进行设计和开发: #### 1. 配置插件 在 `app.json` 文件中引入百度地图插件,完成必要的权限配置。以下是具体的配置代码[^2]: ```json { "plugins": { "chooseLocation": { "version": "1.0.10", "provider": "wx76a9a06e5b4e693e" } }, "permission": { "scope.userLocation": { "desc": "你的位置信息将用于小程序定位" } } } ``` #### 2. 获取当前位置 通过调用 `wx.getLocation` 方法获取用户的地理位置信息。此方法支持两种坐标系:`wgs84` 和 `gcj02`。为了与百度地图兼容,建议使用 `gcj02` 坐标系[^2]。 示例代码如下: ```javascript wx.getLocation({ type: 'gcj02', success: (res) => { const { latitude, longitude } = res; console.log(`纬度: ${latitude}, 经度: ${longitude}`); // 将经纬度传递给后续逻辑 navigateToBaiduMap(latitude, longitude); }, fail: (error) => { console.error('获取位置失败:', error); } }); ``` #### 3. 构建跳转链接 构建一个 URL 地址,指向百度地图的应用程序或网页端。可以利用百度地图开放平台提供的接口来生成导航地址。例如,假设目标地点的经纬度已知,则可通过以下方式构造 URL: ```javascript function generateBaiduMapUrl(startLatitude, startLongitude, endLatitude, endLongitude) { return `baidumap://map/direction?origin=latlng:${startLatitude},${startLongitude}|name:我的位置&destination=latlng:${endLatitude},${endLongitude}|name:目的地&mode=driving`; } const baiduMapUrl = generateBaiduMapUrl(latitude, longitude, targetLatitude, targetLongitude); console.log(baiduMapUrl); ``` #### 4. 执行跳转操作 如果设备安装了百度地图应用,则可以直接打开该应用程序;如果没有安装,则可引导用户访问百度地图 H5 页面。具体实现如下: ```javascript function openBaiduMap(url) { wx.getSystemInfo({ success: (sysRes) => { if (sysRes.platform === 'android') { wx.navigateTo({ url: `/pages/webview/webview?url=${encodeURIComponent(url)}` }); } else if (sysRes.platform === 'ios') { try { wx.openDocument({ filePath: url, fileType: 'html' }); } catch (err) { wx.showToast({ title: '请手动打开百度地图', icon: 'none' }); } } } }); } openBaiduMap(baiduMapUrl); ``` #### 5. 使用 Uni-app 提供的地图 API 对于更通用的情况,也可以考虑使用 Uni-app 的 `uni.openLocation` 接口,在不依赖特定第三方应用的情况下提供基础的地图导航能力[^3]。不过需要注意的是,这种方式仅能显示指定位置而无法直接触发导航行为。 ```javascript uni.openLocation({ latitude: parseFloat(targetLatitude), longitude: parseFloat(targetLongitude), name: '目的地名称', address: '详细地址描述', scale: 18, success() { console.log('成功打开位置'); }, fail(err) { console.error('打开位置失败', err); } }); ``` --- ### 总结 以上方案分别介绍了如何基于原生微信小程序插件以及跨平台框架 Uni-app 来实现从微信小程序跳转到百度地图开启导航的功能。开发者可以根据实际需求选择合适的实现路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值