苹果原生地图集成基本功能

目前APP端能够集成的地图国内的有百度,高德,国外的有谷歌,但如果做国际化,对安卓开发来说就要接入两种地图 (由于天朝的规定,大家都懂得) 但对于苹果地图开发来说 苹果地图就能满足这种需求,话不多说, 代码走起!

1.接入苹果原生地图首先要导入#import <MapKit/MapKit.h>  并且实现MKMapViewDelegate,CLLocationManagerDelegate 代理
1.1 创建地图
- (void)creatMap{

    _map = [[MKMapView alloc]initWithFrame:self.bounds];

    _map.delegate=self;

    _map.userTrackingMode = MKUserTrackingModeFollow;

    //显示指南针

    _map.showsCompass = YES;

    //显示比例尺

    _map.showsScale = YES;

    //显示交通状况

    _map.showsTraffic = YES;

    //显示建筑物

    _map.showsBuildings = YES;

    //显示用户所在的位置

    _map.showsUserLocation = YES;

    //显示感兴趣的东西

    _map.showsPointsOfInterest = YES;

    [self addSubview:_map];





    _addressLabel = [[UILabel alloc]init];

    _addressLabel.bounds=CGRectMake(0,0,200,40);

    _addressLabel.backgroundColor = [UIColor blackColor];

    _addressLabel.textColor = [UIColor whiteColor];

    _addressLabel.center = self.center;

    [self addSubview:_addressLabel];



    UITextField*keywordSearchButton = [[UITextFieldalloc]init];

    keywordSearchButton.backgroundColor= [UIColorlightGrayColor];

    keywordSearchButton.frame=CGRectMake(100,64,100,40);

    [keywordSearchButtonaddTarget:self action:@selector(keywordSearch:) forControlEvents:UIControlEventEditingChanged];

    [selfaddSubview:keywordSearchButton];


    UIButton *hotSearchButton = [UIButton buttonWithType:UIButtonTypeCustom];

    hotSearchButton.frame=CGRectMake(0,64,100,40);

    [hotSearchButtonsetTitle:@"热点搜索"forState:UIControlStateNormal];

    [hotSearchButtonaddTarget:self action:@selector(hotSeatch) forControlEvents:UIControlEventTouchUpInside];

    [selfaddSubview:hotSearchButton];



    _placetab = [[UITableView alloc]initWithFrame:CGRectMake(0, 100, self.frame.size.width, 300)];

    _placetab.delegate = self;

    _placetab.dataSource = self;

    _placetab.hidden = YES;

    [self addSubview:_placetab];


    _geoCoder= [[CLGeocoderalloc]init];

}

1.2 实现代理
//每次调用,都会把用户的最新位置(userLocation参数)传进来

- (void)mapView:(MKMapView*)mapView didUpdateUserLocation:(MKUserLocation*)userLocation{


}

- (void)mapView:(MKMapView*)mapView regionWillChangeAnimated:(BOOL)animated{


    //    JKAnnotation *anno = [[JKAnnotation alloc] init];

    //    anno.title = @"我是一个大头针";

    //    anno.subtitle = @"我有一个小弟叫小头";

    //    anno.coordinate = CLLocationCoordinate2DMake(mapView.centerCoordinate.latitude, mapView.centerCoordinate.longitude);

    //    [mapView addAnnotation:anno];


    CLLocation *currLocation = [[CLLocation alloc]initWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];

    [_geoCoderreverseGeocodeLocation:currLocationcompletionHandler:^(NSArray*placemarks,NSError*error) {


        for(CLPlacemark* placemarkinplacemarks) {


            NSDictionary*address = [placemarkaddressDictionary];

            _addressLabel.text= [addressobjectForKey:@"Name"];

            NSLog(@"%@", [addressobjectForKey:@"Name"]);

        }


    }];


    NSLog(@"------%f",mapView.centerCoordinate.latitude);

}


2.定位功能

如果想单一实现定位功能 系统有一个 CLLocationManager 实现CLLocationManagerDelegate
2.1 开始定位
-(void)startLocation{


    if ([CLLocationManager locationServicesEnabled]) {//判断定位操作是否被允许


        self.locationManager= [[CLLocationManageralloc]init];


        self.locationManager.delegate = self;//遵循代理


        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;


        self.locationManager.distanceFilter = 10.0f;


        [_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据(iOS8以上版本定位需要)


        [self.locationManager startUpdatingLocation];//开始定位


    }else{//不能定位用户的位置的情况再次进行判断,并给与用户提示


        //1.提醒用户检查当前的网络状况


        //2.提醒用户打开定位开关


    }


}

//实现代理
- (void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations{


    //当前所在城市的坐标值

    CLLocation*currLocation = [locationslastObject];

    NSLog(@"经度=%f 纬度=%f 高度=%f", currLocation.coordinate.latitude,currLocation.coordinate.longitude,currLocation.altitude);


    //根据经纬度反向地理编译出地址信息

    CLGeocoder* geoCoder = [[CLGeocoderalloc]init];


    [geoCoderreverseGeocodeLocation:currLocationcompletionHandler:^(NSArray*placemarks,NSError*error) {


        for(CLPlacemark* placemarkinplacemarks) {


            NSDictionary*address = [placemarkaddressDictionary];


            //  Country(国家)  State(省)  City(市)

            NSLog(@"#####%@",address);


            NSLog(@"%@", [addressobjectForKey:@"Country"]);


            NSLog(@"%@", [addressobjectForKey:@"State"]);


            NSLog(@"%@", [addressobjectForKey:@"City"]);



        }


    }];


}


-(void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error{


    if([errorcode] ==kCLErrorDenied){

        //访问被拒绝

    }

    if ([error code] == kCLErrorLocationUnknown) {

        //无法获取位置信息

    }

}

3.搜索功能
//关键字搜索

- (void)keywordSearch:(UITextField*)field {

    if(field.text.length==0){

        _placetab.hidden=YES;

    }

    //创建地理编码

    CLGeocoder*geocoder = [[CLGeocoderalloc]init];

    //正向地理编码

    [geocodergeocodeAddressString:field.textcompletionHandler:^(NSArray*_Nullableplacemarks,NSError*_Nullableerror) {


        if(error ==nil) {

            //解析地理位置成功

            //成功后遍历数组

            for(CLPlacemark*placeinplacemarks) {


                //创建大头针


                //                                MyPointAnnotation *annotation = [[MyPointAnnotation alloc] initWithCoorDinate:place.location.coordinate title:place.name subTitle:place.locality information:place.locality];

                //                                //将大头针加入到地图

                //                                [_map addAnnotation:annotation];

                [self.dataArrayremoveAllObjects];

                [self.dataArrayaddObject:place];

                _placetab.hidden=NO;

                [_placetabreloadData];





            }


        }else{


            NSLog(@"正向地理编码解析失败");

        }


    }];


}
//热门搜索

- (void)hotSeatch {

    //创建本地搜索请求

    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];

    //设置搜索热点词(自然语言)

    request.naturalLanguageQuery = @"学校";

    //设置搜索范围,以某个原点为中心,向外扩展一段经纬度距离范围

    CLLocationCoordinate2D origionpoint = CLLocationCoordinate2DMake(36.08397, 120.37126);

    //设置经纬度跨越范围

    MKCoordinateSpan span = MKCoordinateSpanMake(0.3, 0.3);

    //设置经纬度搜索区域

    MKCoordinateRegionregion =MKCoordinateRegionMake(origionpoint, span);

    //将区域赋值给搜索请求对象中的region属性中

    request.region= region;

    //将地图移动到该区域

    [_mapsetRegion:region];


    //创建本地搜索对象

    MKLocalSearch*search = [[MKLocalSearchalloc]initWithRequest:request];

    //开启搜索

    [searchstartWithCompletionHandler:^(MKLocalSearchResponse*_Nullableresponse,NSError*_Nullableerror) {


        if(error ==nil) {


            //搜索成功

            //获取搜索结果

            NSArray*arrResult = response.mapItems;


            for(MKMapItem*iteminarrResult) {


                //先取出地图目的坐标对象(标记)

                MKPlacemark*placeMark = item.placemark;

                /*

                 96                  地标里存放的经纬度,以及位置的地理信息说明,如名字、街道等等

                 97                  */

                //创建大头针

                JKAnnotation*anno = [[JKAnnotationalloc]init];

                anno.title=@"我是一个大头针";

                anno.subtitle=@"我有一个小弟叫小头";

                anno.coordinate= placeMark.location.coordinate;

                [_mapaddAnnotation:anno];


            }



        }else{

            NSLog(@"搜索失败");


        }


    }];


}
4.自定义大头针 JKAnnotation
.h

#import <Foundation/Foundation.h>

#import<MapKit/MapKit.h>

@interface JKAnnotation : NSObject<MKAnnotation>

@property (nonatomic) CLLocationCoordinate2D coordinate;

@property (nonatomic, copy, nullable) NSString *title;

@property (nonatomic, copy, nullable) NSString *subtitle;

@end

.m
#import "JKAnnotation.h"

@implementation JKAnnotation

@end


// 已经添加了大头针模型,还没有完全渲染出来之前(mapView的代理)

- (void)mapView:(MKMapView*)mapView didAddAnnotationViews:(NSArray *)views{

    for(MKAnnotationView*annotationViewinviews) {

        //目标位置

        CGRecttargetRect = annotationView.frame;

        //先让其在最顶上

        annotationView.frame=CGRectMake(targetRect.origin.x,0, targetRect.size.width, targetRect.size.height);

        //最后通过动画展示到最终的目标地方

        [UIView animateWithDuration:0.3 animations:^{

            annotationView.frame= targetRect;

        }];

    }

}//如果不要这种效果这段代码也可以不需要

// 大头针视图的重用,大头针也存在着重用的机制,方便优化内存

// 每次添加大头针都会调用此方法  可以设置大头针的样式

- (MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id)annotation{

    // 判断大头针位置是否在原点,如果是则不加大头针或者添加属于自己特殊图标

    if([annotationisKindOfClass:[MKUserLocationclass]]) {returnnil; }

    //1.定义一个可重用标识符

    staticNSString*reuseIdentifier =@"mapView";

    MKAnnotationView*annotationView = (MKAnnotationView*)[mapViewdequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];

    if(annotationView ==nil) {

        annotationView = [[MKAnnotationViewalloc]initWithAnnotation:annotationreuseIdentifier:reuseIdentifier];

    }


    //设置可重用标识符的相关属性

    // 显示标题和副标题

    annotationView.canShowCallout=YES;

    // 设置图片(用户头像,或者商品/超市/汽车/单车等等图片)

    annotationView.image= [UIImageimageNamed:@"header_new"];

    //须导入#import "UIImageView+WebCache.h"头文件

    // [annotationView.image sd_setImageWithURL:[NSURL URLWithString:[dict valueForKey:@"icon"]] placeholderImage:[UIImage imageNamed:@"默认图片"]];



    returnannotationView;


    // 判断大头针位置是否在原点,如果是则不加大头针

    //    if([annotation isKindOfClass:[mapView.userLocation class]]){

    //        return nil;

    //    }

    //    //设置自定义大头针

    //    JKAnnotationView *annotationView = (JKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"otherAnnotationView"];

    //    if (annotationView == nil) {

    //        annotationView = [[JKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"otherAnnotationView"];

    //    }

    //    annotationView.image = [UIImage imageNamed:@"header_new"];


    //  return annotationView;

}
demo 地址:https://github.com/XUDAQUAN/AppleMap

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,841评论 5 472
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,415评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,904评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,051评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,055评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,255评论 1 278
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,729评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,377评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,517评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,420评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,467评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,144评论 3 317
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,735评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,812评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,029评论 1 256
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,528评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,126评论 2 341

推荐阅读更多精彩内容