zoukankan      html  css  js  c++  java
  • iOS 调用地图导航

    在IOS6.0系统后,兼容iOS5.0与iOS6.0地图导航,需要分两个步骤

    #define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)//用来获取手机的系统,判断系统是多少

        CLLocationCoordinate2D startCoor = self.mapView.userLocation.location.coordinate;
        CLLocationCoordinate2D endCoor = CLLocationCoordinate2DMake(startCoor.latitude+0.01, startCoor.longitude+0.01);
        
        if (SYSTEM_VERSION_LESS_THAN(@"6.0")) { // ios6以下,调用google map
            
            NSString *urlString = [[NSString alloc] initWithFormat:@"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f&dirfl=d",startCoor.latitude,startCoor.longitude,endCoor.latitude,endCoor.longitude];
            //        @"http://maps.apple.com/?saddr=%f,%f&daddr=%f,%f",startCoor.latitude,startCoor.longitude,endCoor.latitude,endCoor.longitude
            urlString =  [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *aURL = [NSURL URLWithString:urlString];
            [[UIApplication sharedApplication] openURL:aURL];
        } else { // 直接调用ios自己带的apple map
            
            MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
            MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:endCoor addressDictionary:nil]];
            toLocation.name = @"to name";
            
            [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                           launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
            
        }
    

      

    如果不想使用苹果自带的地图的话,也可以使用第三方的地图,如百度、Google Maps、高德等

    使用前,先判断设备上是否已安装应用

    百度地图:

    if ([[UIApplicationsharedApplication]canOpenURL:[NSURLURLWithString:@"baidumap://map/"]])

    参考

    高德地图:

    if ([[UIApplicationsharedApplication]canOpenURL:[NSURLURLWithString:@"iosamap://"]])

    参考

    Google Maps:

    if ([[UIApplicationsharedApplication]canOpenURL:[NSURLURLWithString:@"comgooglemaps://"]])

    参考

    示例代码

    - (void)availableMapsApps {
        [self.availableMaps removeAllObjects];
        
        CLLocationCoordinate2D startCoor = self.mapView.userLocation.location.coordinate;
        CLLocationCoordinate2D endCoor = CLLocationCoordinate2DMake(startCoor.latitude+0.01, startCoor.longitude+0.01);
        NSString *toName = @"to name";
        
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]){
            NSString *urlString = [NSString stringWithFormat:@"baidumap://map/direction?origin=latlng:%f,%f|name:我的位置&destination=latlng:%f,%f|name:%@&mode=transit",
                                   startCoor.latitude, startCoor.longitude, endCoor.latitude, endCoor.longitude, toName];
            
            NSDictionary *dic = @{@"name": @"百度地图",
                                  @"url": urlString};
            [self.availableMaps addObject:dic];
        }
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
            NSString *urlString = [NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=applicationScheme&poiname=fangheng&poiid=BGVIS&lat=%f&lon=%f&dev=0&style=3",
                                   @"云华时代", endCoor.latitude, endCoor.longitude];
            
            NSDictionary *dic = @{@"name": @"高德地图",
                                  @"url": urlString};
            [self.availableMaps addObject:dic];
        }
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {
            NSString *urlString = [NSString stringWithFormat:@"comgooglemaps://?saddr=&daddr=%f,%f¢er=%f,%f&directionsmode=transit", endCoor.latitude, endCoor.longitude, startCoor.latitude, startCoor.longitude];
            
            NSDictionary *dic = @{@"name": @"Google Maps",
                                  @"url": urlString};
            [self.availableMaps addObject:dic];
        }
    }
    

      显示一个ActionSheet

    [self availableMapsApps];
        UIActionSheet *action = [[UIActionSheet alloc] init];
        
        [action addButtonWithTitle:@"使用系统自带地图导航"];
        for (NSDictionary *dic in self.availableMaps) {
            [action addButtonWithTitle:[NSString stringWithFormat:@"使用%@导航", dic[@"name"]]];
        }
        [action addButtonWithTitle:@"取消"];
        action.cancelButtonIndex = self.availableMaps.count + 1;
        action.delegate = self;
        [action showInView:self.view];
    

      实现delegate

    - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
        if (buttonIndex == 0) {
            CLLocationCoordinate2D startCoor = self.mapView.userLocation.location.coordinate;
            CLLocationCoordinate2D endCoor = CLLocationCoordinate2DMake(startCoor.latitude+0.01, startCoor.longitude+0.01);
            
            if (SYSTEM_VERSION_LESS_THAN(@"6.0")) { // ios6以下,调用google map
                
                NSString *urlString = [[NSString alloc] initWithFormat:@"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f&dirfl=d",startCoor.latitude,startCoor.longitude,endCoor.latitude,endCoor.longitude];
                //        @"http://maps.apple.com/?saddr=%f,%f&daddr=%f,%f",startCoor.latitude,startCoor.longitude,endCoor.latitude,endCoor.longitude
                urlString =  [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                NSURL *aURL = [NSURL URLWithString:urlString];
                [[UIApplication sharedApplication] openURL:aURL];
            } else{// 直接调用ios自己带的apple map
                
                MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
                MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:endCoor addressDictionary:nil];
                MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:placemark];
                toLocation.name = @"to name";
                
                [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                               launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
                
            }
        }else if (buttonIndex < self.availableMaps.count+1) {
            NSDictionary *mapDic = self.availableMaps[buttonIndex-1];
            NSString *urlString = mapDic[@"url"];
            urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url = [NSURL URLWithString:urlString];
            DEBUG_LOG(@"
    %@
    %@
    %@", mapDic[@"name"], mapDic[@"url"], urlString);
            [[UIApplication sharedApplication] openURL:url];
        }
    }
    
    #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
    

      

      

  • 相关阅读:
    字符串----不可重叠的最长重复子串
    字符串----最长重复子串
    字符串----HDU-1358
    字符串----hiho字符串(尺取法)
    字符串匹配(二)----KMP算法
    字符串匹配(一)----Rabin-Karp算法
    字符串----最短摘要生成(尺取法)
    【Hibernate 检索策略】
    【Hibernate 多表查询】
    【Hibernate QBC】
  • 原文地址:https://www.cnblogs.com/mgbert/p/4042695.html
Copyright © 2011-2022 走看看