iOS開發之地圖-添加多個大頭針及自定義大頭針視圖

前言
學習地圖,我們必須要接觸兩個框架:
Core Location,主要包含定位、地理編碼、反編碼功能,如需了解請移步iOS開發之地圖-定位/編碼與反編碼
MapKit,利用他可以對地圖進行精準的控制,比如,放置大頭針、地圖類型切換,導航等等。
本文我們主要介紹的是使用MapKit框架對地圖試圖進行精準的控制。
如果無法顯示自己的位置,檢查以下幾點:
是否將定位管理器設為全局變量
是否在項目中進行定位授權,是否在Info.plist中配置
是否將showsUserLocation設為YES。
是否配置模擬器 點擊模擬器 -> 菜單欄Dubug -> Location -> Apple來使模擬器定位,然后使用Custom Location配置模擬器的經緯度。

添加多個大頭針及自定義大頭針視圖代碼示例:
此鏈接下是自定義大頭針的Demo可自行下載
ViewController.m(.h聲明文件中沒有寫代碼)

    //
    //  ViewController.m
    //  CustomeAnnotationView
    //
    //  Created by 王龍 on 16/3/19.
    //  Copyright ? 2016年 Larry(Lawrence). All rights reserved.
    //

    #import "ViewController.h"
    #import <MapKit/MapKit.h>
    #import <CoreLocation/CoreLocation.h>
    #import "MyAnnotation.h"
    #import "CustomPinAnnotationView.h"

    @interface ViewController ()<MKMapViewDelegate>
    {
        CLLocationManager *_locationManager;
        MKMapView *_mapView;
    }

    @property (nonatomic,retain) NSMutableArray *locationArray;

    @end
    @implementation ViewController

    - (void)viewDidLoad {
        [super viewDidLoad];

    //    定位授權

        _locationManager = [[CLLocationManager alloc]init];
        [_locationManager requestWhenInUseAuthorization];
    //    地圖視圖
        _mapView = [[MKMapView alloc]initWithFrame:self.view.frame];
        _mapView.showsUserLocation = YES;
        _mapView.delegate = self;
        [self.view addSubview:_mapView];  
    }

    - (void)loadData{
        NSString *filePath = [[NSBundle mainBundle]pathForResource:@"PinData" ofType:@"plist"];
        NSArray *tempArray = [NSArray arrayWithContentsOfFile:filePath];

    //    把plist數據轉換成大頭針model
        for (NSDictionary *dict in tempArray) {
            MyAnnotation *myAnnotationModel = [[MyAnnotation alloc]initWithAnnotationModelWithDict:dict];
    
            [self.locationArray addObject:myAnnotationModel];
        }

    //    核心代碼
        [_mapView addAnnotations:self.locationArray];
    }

    #pragma mark ------ delegate
    - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
userLocation.title  =@"你好";

        _mapView.centerCoordinate = userLocation.coordinate;

        [_mapView setRegion:MKCoordinateRegionMake(userLocation.coordinate, MKCoordinateSpanMake(0.3, 0.3)) animated:YES];
    //    如果在ViewDidLoad中調用  添加大頭針的話會沒有掉落效果  定位結束后再添加大頭針才會有掉落效果
        [self loadData];

    }

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

        /*
 
         * 大頭針分兩種
 
         * 1. MKPinAnnotationView:他是系統自帶的大頭針,繼承于MKAnnotationView,形狀跟棒棒糖類似,可以設置糖的顏色,和顯示的時候是否有動畫效果
 
         * 2. MKAnnotationView:可以用指定的圖片作為大頭針的樣式,但顯示的時候沒有動畫效果,如果沒有給圖片的話會什么都不顯示
 
         * 3. mapview有個代理方法,當大頭針顯示在試圖上時會調用,可以實現這個方法來自定義大頭針的動畫效果,我下面寫有可以參考一下
 
         * 4. 在這里我為了自定義大頭針的樣式,使用的是MKAnnotationView
 
         */


        //    判斷是不是用戶的大頭針數據模型
        if ([annotation isKindOfClass:[MKUserLocation class]]) {
            MKAnnotationView *annotationView = [[MKAnnotationView alloc]init];
            annotationView.image = [UIImage imageNamed:@"acc"];
    
    //        是否允許顯示插入視圖*********
            annotationView.canShowCallout = YES;
    
            return annotationView;
        }

        CustomPinAnnotationView *annotationView = (CustomPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"otherAnnotationView"];
if (annotationView == nil) {
    annotationView = [[CustomPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"otherAnnotationView"];
}
        MyAnnotation *myAnnotation = annotation;
        switch ([myAnnotation.type intValue]) {
            case SUPER_MARKET:
                annotationView.image = [UIImage imageNamed:@"super"];
                annotationView.label.text = @"超市";
                break;
            case CREMATORY:
                annotationView.image = [UIImage imageNamed:@"chang"];
                annotationView.label.text = @"火場";
                break;
            case INTEREST:
                annotationView.image = [UIImage imageNamed:@"jingqu"];
                annotationView.label.text = @"風景區";
        break;
        
            default:
                break;
        }

        return annotationView;
    }


            //大頭針顯示在視圖上時調用,在這里給大頭針設置顯示動畫
    - (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray<MKAnnotationView *> *)views{
    //    獲得mapView的Frame
        CGRect visibleRect = [mapView annotationVisibleRect];
        for (MKAnnotationView *view in views) {
    
            CGRect endFrame = view.frame;
            CGRect startFrame = endFrame;
            startFrame.origin.y = visibleRect.origin.y - startFrame.size.height;
            view.frame = startFrame;
            [UIView beginAnimations:@"drop" context:NULL];
            [UIView setAnimationDuration:1];
            view.frame = endFrame;
            [UIView commitAnimations];
        }
    }

    #pragma mark lazy load

    - (NSMutableArray *)locationArray{

        if (_locationArray == nil) {
    
            _locationArray = [NSMutableArray new];
    
        }
        return _locationArray;
    }

    @end

MyAnnotation.h中

    //
    //  MyAnnotation.h
    //  CustomeAnnotationView
    //
    //  Created by 王龍 on 16/3/19.
    //  Copyright ? 2016年 Larry(Lawrence). All rights reserved.
    //

    #import <Foundation/Foundation.h>

    //注意導入框架

    #import <MapKit/MapKit.h>

    /**
     *  大頭針枚舉
     */
    typedef NS_ENUM(NSInteger,PinType) {
        /**
         *  超市
         */
        SUPER_MARKET = 0,
        /**
         *  火場
         */
        CREMATORY,
        /**
         *  景點
         */
        INTEREST,
    };

    //該模型是大頭針模型 所以必須實現協議MKAnnotation協議 和CLLocationCoordinate2D中的屬性coordinate
    @interface MyAnnotation : NSObject<MKAnnotation>

    @property (nonatomic,assign) CLLocationCoordinate2D coordinate;
    @property (nonatomic,copy) NSString *name;
    @property (nonatomic,copy) NSString *title;
    @property (nonatomic,retain) NSNumber *type;

    - (instancetype)initWithAnnotationModelWithDict:(NSDictionary *)dict;


    @end

MyAnnotation.m中

    //
    //  MyAnnotation.m
    //  CustomeAnnotationView
    //
    //  Created by 王龍 on 16/3/19.
    //  Copyright ? 2016年 Larry(Lawrence). All rights reserved.
    //

    #import "MyAnnotation.h"

    @implementation MyAnnotation


    - (instancetype)initWithAnnotationModelWithDict:(NSDictionary *)dict{
        self = [super init];
        if (self) {
    
    
            self.coordinate = CLLocationCoordinate2DMake([dict[@"coordinate"][@"latitute"] doubleValue], [dict[@"coordinate"][@"longitude"] doubleValue]);
            self.title = dict[@"detail"];
            self.name = dict[@"name"];
            self.type = dict[@"type"];  
        }
        return self;
    }

    @end

CustomPinAnnotationView.h中

    //
    //  CustomPinAnnotationView.h
    //  CustomeAnnotationView
    //
    //  Created by 王龍 on 16/3/19.
    //  Copyright ? 2016年 Larry(Lawrence). All rights reserved.
    //

    #import <MapKit/MapKit.h>
    #import "MyAnnotation.h"

    @interface CustomPinAnnotationView : MKAnnotationView
    @property (nonatomic,strong) UILabel *label;
    @end

CustomPinAnnotationView.m中

    //
   //  CustomPinAnnotationView.m
   //  CustomeAnnotationView
   //
   //  Created by 王龍 on 16/3/19.
   //  Copyright ? 2016年 Larry(Lawrence). All rights reserved.
   //

   #import "CustomPinAnnotationView.h"

   @implementation CustomPinAnnotationView


   - (instancetype)initWithAnnotation:(id<MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier{
       self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
       if (self) {
    
   //        在大頭針旁邊加一個label
           self.label = [[UILabel alloc]initWithFrame:CGRectMake(0, -15, 50, 20)];
           self.label.textColor = [UIColor redColor];
           self.label.textAlignment = NSTextAlignmentCenter;
           self.label.font = [UIFont systemFontOfSize:20];
           [self addSubview:self.label];
    
       }
       return self;

   }
   @end
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,156評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,401評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,069評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,873評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,635評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,128評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,203評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,365評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,881評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,733評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,935評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,475評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,172評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,582評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,821評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,595評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,908評論 2 372

推薦閱讀更多精彩內容