app 跳转到地图

废话不说,直接上代码

#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface PositionController ()<CLLocationManagerDelegate,MKMapViewDelegate>
{
    //添加代理协议 CLLocationManagerDelegate
    CLLocationManager *_locationManager;//定位服务管理类
}
@property (nonatomic, strong)NSString *position;//现在位置 
@property (nonatomic, assign)CLLocationCoordinate2D Coordinate2D;//现在的坐标 
@property (nonatomic, assign)CLLocationCoordinate2D address;//目的地坐标 
@property (nonatomic, strong)NSString *addressName;//目的地名字 
@property (nonatomic, strong)MKMapView *mapView;//地图
- (MKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(self.space, self.gotoBtn.bottom+self.space, WIDTH-2*self.space, HEIGHT-self.gotoBtn.bottom-2*self.space-64)];
        _mapView.backgroundColor=[[UIColor redColor] colorWithAlphaComponent:0.2];
            /**
               MKMapTypeStandard = 0,  // 标准
               MKMapTypeSatellite,     // 卫星
               MKMapTypeHybrid,        // 混合(标准+卫星)
               MKMapTypeSatelliteFlyover NS_ENUM_AVAILABLE(10_11, 9_0), // 3D立体卫星
               MKMapTypeHybridFlyover NS_ENUM_AVAILABLE(10_11, 9_0), // 3D立体混合
            */
        _mapView.mapType = MKMapTypeStandard;//地图显示类型
        _mapView.userTrackingMode=MKUserTrackingModeFollow;//添加此句,可以自动定位到当前位置
        _mapView.delegate=self;
        _mapView.showsScale = YES;
        // 是否可以缩放
        _mapView.zoomEnabled = YES;
        // 是否可以滚动
        _mapView.scrollEnabled = YES;
        // 是否可以旋转
        _mapView.rotateEnabled = YES;
        // 是否显示3D
        _mapView.pitchEnabled = YES;
    }
    return _mapView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.mapView];
    [self  coordinateTouch];
[self performSelector:@selector(gotoTouch) withObject:nil afterDelay:5];
}
- (void)coordinateTouch{
    _locationManager = [[CLLocationManager alloc] init];
    //    [_locationManager requestWhenInUseAuthorization];
    [_locationManager requestAlwaysAuthorization];//iOS8必须,这两行必须有一行执行,否则无法获取位置信息,和定位
    //    _locationManager.allowsBackgroundLocationUpdates = YES;
    // 设置代理
    _locationManager.delegate = self;
    // 设置定位精确度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置过滤器为无
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    // 开始定位
    [_locationManager startUpdatingLocation];//开始定位之后会不断的执行代理方法更新位置会比较费电所以建议获取完位置即时关闭更新位置服务
    //初始化地理编码器
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    //当前位置
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    self.Coordinate2D=oldCoordinate;
    
    [manager stopUpdatingLocation];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *place in placemarks) {         
            self.position = [NSString stringWithFormat:@"%@ %@ %@ %@",place.country,place.locality,place.subLocality,place.thoroughfare];
            [_positionBtn setTitle:self.position forState:UIControlStateNormal];
            break;
        }
    }];
}
- (void)gotoTouch {
    //目的地
    self.addressName = @"杭州滨江区政府";
    CLGeocoder *geocode = [[CLGeocoder alloc] init];
    
    [geocode geocodeAddressString:self.addressName completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count ] > 0) {
            //移除目前地图上得所有标注点
            [_mapView removeAnnotations:_mapView.annotations];
        }else {
            NSLog(@"找不到此地址");
            return ;
        }
        
        for (int i = 0; i< [placemarks count]; i++) {
            CLPlacemark * placemark = placemarks[i];
            //调整地图位置和缩放比例,第一个参数是目标区域的中心点,第二个参数:目标区域南北的跨度,第三个参数:目标区域的东西跨度,单位都是米
            MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(placemark.location.coordinate, 10000, 10000);
            
            //重新设置地图视图的显示区域
            [_mapView setRegion:viewRegion animated:YES];
            // 实例化 MapLocation 对象
            mapLocation * annotation = [[mapLocation alloc] init];
            annotation.streetAddress = placemark.thoroughfare ;
            annotation.city = placemark.locality;
            annotation.state = placemark.administrativeArea ;
            annotation.zip = placemark.postalCode;
            annotation.coordinate = placemark.location.coordinate;
            annotation.title=placemark.name;
            
            self.address=placemark.location.coordinate;;
            //把标注点MapLocation 对象添加到地图视图上,一旦该方法被调用,地图视图委托方法mapView:ViewForAnnotation:就会被回调
            [_mapView addAnnotation:annotation];

//第一个坐标
            CLLocation *current=[[CLLocation alloc] initWithLatitude:self.Coordinate2D.latitude longitude:self.Coordinate2D.longitude];
            //第二个坐标
            CLLocation *before=[[CLLocation alloc] initWithLatitude:self.address.latitude longitude:self.address.longitude];
            // 计算距离
            CLLocationDistance meters=[current distanceFromLocation:before];
            NSLog(@"计算距离========= %.0f 米",meters);
        }
    }];
    
    [self presentViewController:self.alertController animated:YES completion:nil];
}
-(UIAlertController *)alertController{
    if (!_alertController) {
        _alertController = [UIAlertController alertControllerWithTitle:@"请选择地图" message:nil
                                                        preferredStyle:UIAlertControllerStyleActionSheet ];
        UIAlertAction *appleAction = [UIAlertAction actionWithTitle:@"苹果自带地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
            CLLocationCoordinate2D Coordinate2D ;
            Coordinate2D.latitude = self.address.latitude;
            Coordinate2D.longitude = self.address.longitude;
            MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:Coordinate2D addressDictionary:nil]];
            toLocation.name = self.addressName;
            [MKMapItem openMapsWithItems:@[currentLocation,toLocation] launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
        }];
        UIAlertAction *tecentAction = [UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&poiname=%@&lat=%f&lon=%f&dev=0&style=2",@"住哪儿",@"FXTools",self.addressName,self.address.latitude,self.address.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            }else{
                
            }
        }];
        UIAlertAction *baiduAction = [UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name:%@&mode=driving&coord_type=gcj02",self.address.latitude,self.address.longitude,self.addressName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            if ([[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            }else{
                [MBProgressHUD showMessage:@"您的手机未安装百度地图"];
            }
        }];
        UIAlertAction *tentAction = [UIAlertAction actionWithTitle:@"腾讯地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *urlString = [NSString stringWithFormat:@"qqmap://map/routeplan?type=drive&fromcoord=%f,%f&tocoord=%f,%f&policy=1",self.Coordinate2D.latitude,self.Coordinate2D.longitude,self.address.latitude,self.address.longitude];
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            }else{
                
            }
        }];

        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleCancel handler:nil];
        [_alertController addAction:appleAction];
        [_alertController addAction:tecentAction];
        [_alertController  addAction:baiduAction];
        [_alertController  addAction:tentAction];
        [_alertController addAction:cancelAction];
    }
    return _alertController;
}
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface mapLocation : NSObject<MKAnnotation>
// 地图标点类必须实现 MKAnnotation 协议
// 地理坐标
@property (nonatomic ,readwrite) CLLocationCoordinate2D coordinate ;
//街道属性信息
@property (nonatomic , copy) NSString * streetAddress ;
// 城市信息属性
@property (nonatomic ,copy) NSString * city ;
// 州,省 市 信息
@property(nonatomic ,copy ) NSString * state ;
//邮编
@property (nonatomic ,copy) NSString * zip  ;
@property (nonatomic, copy) NSString *title;
@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • 纷繁世界,五彩缤纷,表里斟酌,朦胧难辨。不想因为想得到想要的东西而失去最不想失去的东西。不想因为想变成想成为的样子...
    活着就是幸福阅读 115评论 0 1
  • 我越来越感觉到,做为一个校长,我最最最最重要的工作,就是要哄我的老师们开心。你开心了,才有班上的孩子们的开心。孩子...
    迪子和我阅读 143评论 0 0
  • 文/逗逗,图/花瓣网 1 新品牌新气象,再度扬帆起航。 这几天的朋友圈,不是很风平浪静,连续几天,被之前公司同事的...
    遇见逗逗阅读 124评论 0 0
  • 废旧的作业本,黄昏的天际 是谁放飞了纸飞机, 留下了痕迹。 那是岁月的尾巴,拖着纯真的孩子气, 那是梦想的轨道,通...
    公子凌希阅读 301评论 0 9