1. 程式人生 > >iOS開發系列--地圖與定位

iOS開發系列--地圖與定位

概覽

現在很多社交、電商、團購應用都引入了地圖和定位功能,似乎地圖功能不再是地圖應用和導航應用所特有的。的確,有了地圖和定位功能確實讓我們的生活更加豐富多彩,極大的改變了我們的生活方式。例如你到了一個陌生的地方想要查詢附近的酒店、超市等就可以開啟軟體搜尋周邊;類似的,還有很多團購軟體可以根據你所在的位置自動為你推薦某些商品。總之,目前地圖和定位功能已經大量引入到應用開發中。今天就和大家一起看一下iOS如何進行地圖和定位開發。

  1. 定位
  2. 地圖

定位

要實現地圖、導航功能,往往需要先熟悉定位功能,在iOS中通過Core Location框架進行定位操作。Core Location自身可以單獨使用,和地圖開發框架MapKit完全是獨立的,但是往往地圖開發要配合定位框架使用。在Core Location中主要包含了定位、地理編碼(包括反編碼)功能。

定位功能

定位是一個很常用的功能,如一些地圖軟體開啟之後如果使用者允許軟體定位的話,那麼開啟軟體後就會自動鎖定到當前位置,如果使用者手機移動那麼當前位置也會跟隨著變化。要實現這個功能需要使用Core Loaction中CLLocationManager類,首先看一下這個類的一些主要方法和屬性:

類方法 說明
+ (BOOL)locationServicesEnabled; 是否啟用定位服務,通常如果使用者沒有啟用定位服務可以提示使用者開啟定位服務
+ (CLAuthorizationStatus)authorizationStatus; 定位服務授權狀態,返回列舉型別:
kCLAuthorizationStatusNotDetermined: 使用者尚未做出決定是否啟用定位服務
kCLAuthorizationStatusRestricted: 沒有獲得使用者授權使用定位服務,可能使用者沒有自己禁止訪問授權
kCLAuthorizationStatusDenied :使用者已經明確禁止應用使用定位服務或者當前系統定位服務處於關閉狀態
kCLAuthorizationStatusAuthorizedAlways: 應用獲得授權可以一直使用定位服務,即使應用不在使用狀態
kCLAuthorizationStatusAuthorizedWhenInUse: 使用此應用過程中允許訪問定位服務
屬性 說明
desiredAccuracy 定位精度,列舉型別:

kCLLocationAccuracyBest:最精確定位
CLLocationAccuracy kCLLocationAccuracyNearestTenMeters:十米誤差範圍
kCLLocationAccuracyHundredMeters:百米誤差範圍
kCLLocationAccuracyKilometer:千米誤差範圍
kCLLocationAccuracyThreeKilometers:三千米誤差範圍

distanceFilter 位置資訊更新最小距離,只有移動大於這個距離才更新位置資訊,預設為kCLDistanceFilterNone:不進行距離限制
物件方法 說明
startUpdatingLocation 開始定位追蹤,開始定位後將按照使用者設定的更新頻率執行-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;方法反饋定位資訊
stopUpdatingLocation 停止定位追蹤
startUpdatingHeading 開始導航方向追蹤
stopUpdatingHeading 停止導航方向追蹤
startMonitoringForRegion: 開始對某個區域進行定位追蹤,開始對某個區域進行定位後。如果使用者進入或者走出某個區域會呼叫- (void)locationManager:(CLLocationManager *)manager
    didEnterRegion:(CLRegion *)region
- (void)locationManager:(CLLocationManager *)manager
    didExitRegion:(CLRegion *)region
代理方法反饋相關資訊
stopMonitoringForRegion: 停止對某個區域進行定位追蹤
requestWhenInUseAuthorization 請求獲得應用使用時的定位服務授權,注意使用此方法前在要在info.plist中配置NSLocationWhenInUseUsageDescription
requestAlwaysAuthorization 請求獲得應用一直使用定位服務授權,注意使用此方法前要在info.plist中配置NSLocationAlwaysUsageDescription
代理方法 說明
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations; 位置發生改變後執行(第一次定位到某個位置之後也會執行)
- (void)locationManager:(CLLocationManager *)manager
       didUpdateHeading:(CLHeading *)newHeading;
導航方向發生變化後執行
  - (void)locationManager:(CLLocationManager *)manager
    didEnterRegion:(CLRegion *)region
進入某個區域之後執行
- (void)locationManager:(CLLocationManager *)manager
    didExitRegion:(CLRegion *)region
走出某個區域之後執行

iOS 8 還提供了更加人性化的定位服務選項。App 的定位服務不再僅僅是關閉或開啟,現在,定位服務的啟用提供了三個選項,「永不」「使用應用程式期間」和「始終」。同時,考慮到能耗問題,如果一款 App 要求始終能在後臺開啟定位服務,iOS 8 不僅會在首次開啟 App 時主動向你詢問,還會在日常使用中彈窗提醒你該 App 一直在後臺使用定位服務,並詢問你是否繼續允許。在iOS7及以前的版本,如果在應用程式中使用定位服務只要在程式中呼叫startUpdatingLocation方法應用就會詢問使用者是否允許此應用是否允許使用定位服務,同時在提示過程中可以通過在info.plist中配置通過配置Privacy - Location Usage Description告訴使用者使用的目的,同時這個配置是可選的。
但是在iOS8中配置配置項發生了變化,可以通過配置NSLocationAlwaysUsageDescription或者NSLocationWhenInUseUsageDescription來告訴使用者使用定位服務的目的,並且注意這個配置是必須的,如果不進行配置則預設情況下應用無法使用定位服務,開啟應用不會給出開啟定位服務的提示,除非安裝後自己設定此應用的定位服務。同時,在應用程式中需要根據配置對requestAlwaysAuthorization或locationServicesEnabled方法進行請求。由於本人機器已經更新到最新的iOS8.1下面的內容主要針對iOS8,使用iOS7的朋友需要稍作調整。 

//
//  KCMainViewController.m
//  CoreLocation
//
//  Created by Kenshin Cui on 14-03-27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//

#import "KCMainViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface KCMainViewController ()<CLLocationManagerDelegate>{

    CLLocationManager *_locationManager;
}

@end

@implementation KCMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //定位管理器
    _locationManager=[[CLLocationManager alloc]init];
    
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服務當前可能尚未開啟,請設定開啟!");
        return;
    }
    
    //如果沒有授權則請求使用者授權
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
        [_locationManager requestWhenInUseAuthorization];
    }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
        //設定代理
        _locationManager.delegate=self;
        //設定定位精度
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        //定位頻率,每隔多少米定位一次
        CLLocationDistance distance=10.0;//十米定位一次
        _locationManager.distanceFilter=distance;
        //啟動跟蹤定位
        [_locationManager startUpdatingLocation];
    }
}

#pragma mark - CoreLocation 代理
#pragma mark 跟蹤定位代理方法,每次位置發生變化即會執行(只要定位到相應位置)
//可以通過模擬器設定一個虛擬位置,否則在模擬器中無法呼叫此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=[locations firstObject];//取出第一個位置
    CLLocationCoordinate2D coordinate=location.coordinate;//位置座標
    NSLog(@"經度:%f,緯度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
    //如果不需要實時定位,使用完即使關閉定位服務
    [_locationManager stopUpdatingLocation];
}

@end

注意:

1.定位頻率和定位精度並不應當越精確越好,需要視實際情況而定,因為越精確越耗效能,也就越費電。

2.定位成功後會根據設定情況頻繁呼叫-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations方法,這個方法返回一組地理位置物件陣列,每個元素一個CLLocation代表地理位置資訊(包含經度、緯度、海報、行走速度等資訊),之所以返回陣列是因為有些時候一個位置點可能包含多個位置。

3.使用完定位服務後如果不需要實時監控應該立即關閉定位服務以節省資源。

4.除了提供定位功能,CLLocationManager還可以呼叫startMonitoringForRegion:方法對指定區域進行監控。

地理編碼

除了提供位置跟蹤功能之外,在定位服務中還包含CLGeocoder類用於處理地理編碼和逆地理編碼(又叫反地理編碼)功能。

地理編碼:根據給定的位置(通常是地名)確定地理座標(經、緯度)。

逆地理編碼:可以根據地理座標(經、緯度)確定位置資訊(街道、門牌等)。

CLGeocoder最主要的兩個方法就是- (void)geocodeAddressString:(NSString *)addressString completionHandler:(CLGeocodeCompletionHandler)completionHandler;- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;,分別用於地理編碼和逆地理編碼。下面簡單演示一下:

//
//  KCMainViewController.m
//  CoreLocation
//
//  Created by Kenshin Cui on 14-03-27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//

#import "KCMainViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface KCMainViewController ()<CLLocationManagerDelegate>{

    CLGeocoder *_geocoder;
}

@end

@implementation KCMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _geocoder=[[CLGeocoder alloc]init];
    [self getCoordinateByAddress:@"北京"];
    [self getAddressByLatitude:39.54 longitude:116.28];
}

#pragma mark 根據地名確定地理座標
-(void)getCoordinateByAddress:(NSString *)address{
    //地理編碼
    [_geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
        //取得第一個地標,地標中儲存了詳細的地址資訊,注意:一個地名可能搜尋出多個地址
        CLPlacemark *placemark=[placemarks firstObject];
        
        CLLocation *location=placemark.location;//位置
        CLRegion *region=placemark.region;//區域
        NSDictionary *addressDic= placemark.addressDictionary;//詳細地址資訊字典,包含以下部分資訊
//        NSString *name=placemark.name;//地名
//        NSString *thoroughfare=placemark.thoroughfare;//街道
//        NSString *subThoroughfare=placemark.subThoroughfare; //街道相關資訊,例如門牌等
//        NSString *locality=placemark.locality; // 城市
//        NSString *subLocality=placemark.subLocality; // 城市相關資訊,例如標誌性建築
//        NSString *administrativeArea=placemark.administrativeArea; // 州
//        NSString *subAdministrativeArea=placemark.subAdministrativeArea; //其他行政區域資訊
//        NSString *postalCode=placemark.postalCode; //郵編
//        NSString *ISOcountryCode=placemark.ISOcountryCode; //國家編碼
//        NSString *country=placemark.country; //國家
//        NSString *inlandWater=placemark.inlandWater; //水源、湖泊
//        NSString *ocean=placemark.ocean; // 海洋
//        NSArray *areasOfInterest=placemark.areasOfInterest; //關聯的或利益相關的地標
        NSLog(@"位置:%@,區域:%@,詳細資訊:%@",location,region,addressDic);
    }];
}

#pragma mark 根據座標取得地名
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
    //反地理編碼
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark=[placemarks firstObject];
        NSLog(@"詳細資訊:%@",placemark.addressDictionary);
    }];
}

@end

地圖

iOS從6.0開始地圖資料不再由谷歌驅動,而是改用自家地圖,當然在國內它的資料是由高德地圖提供的。這樣一來,如果在iOS6.0之前進行地圖開發的話使用方法會有所不同,基於目前的情況其實使用iOS6.0之前版本的系統基本已經寥寥無幾了,所有在接下來的內容中不會再針對iOS5及之前版本的地圖開發進行介紹。

在iOS中進行地圖開發主要有兩種方式,一種是直接利用MapKit框架進行地圖開發,利用這種方式可以對地圖進行精準的控制;另一種方式是直接呼叫蘋果官方自帶的地圖應用,主要用於一些簡單的地圖應用(例如:進行導航覆蓋物填充等),無法進行精確的控制。當然,本節重點內容還是前者,後面的內容也會稍加提示。

用MapKit之前需要簡單瞭解一下MapKit中地圖展示控制元件MKMapView的的一些常用屬性和方法,具體如下表: 
屬性 說明
userTrackingMode 跟蹤型別,是一個列舉:
MKUserTrackingModeNone :不進行使用者位置跟蹤;
MKUserTrackingModeFollow :跟蹤使用者位置;
MKUserTrackingModeFollowWithHeading :跟蹤使用者位置並且跟蹤使用者前進方向;
mapType 地圖型別,是一個列舉:
MKMapTypeStandard :標準地圖,一般情況下使用此地圖即可滿足;
MKMapTypeSatellite :衛星地圖;
MKMapTypeHybrid :混合地圖,載入最慢比較消耗資源;
userLocation 使用者位置,只讀屬性
annotations 當前地圖中的所有大頭針,只讀屬性
物件方法 說明
- (void)addAnnotation:(id <MKAnnotation>)annotation; 新增大頭針,對應的有新增大頭針陣列
- (void)removeAnnotation:(id <MKAnnotation>)annotation; 刪除大頭針,對應的有刪除大頭針陣列

- (void)setRegion:(MKCoordinateRegion)region animated:(BOOL)animated;

設定地圖顯示區域,用於控制當前螢幕顯示地圖範圍
- (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated; 設定地圖中心點位置
- (CGPoint)convertCoordinate:(CLLocationCoordinate2D)coordinate toPointToView:(UIView *)view; 將地理座標(經緯度)轉化為數學座標(UIKit座標)
- (CLLocationCoordinate2D)convertPoint:(CGPoint)point toCoordinateFromView:(UIView *)view; 將數學座標轉換為地理座標
- (MKAnnotationView *)dequeueReusableAnnotationViewWithIdentifier:(NSString *)identifier; 從快取池中取出大頭針,類似於UITableView中取出UITableViewCell,為了進行效能優化而設計
- (void)selectAnnotation:(id <MKAnnotation>)annotation animated:(BOOL)animated; 選中指定的大頭針
- (void)deselectAnnotation:(id <MKAnnotation>)annotation animated:(BOOL)animated; 取消選中指定的大頭針
代理方法 說明
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation ; 使用者位置發生改變時觸發(第一次定位到使用者位置也會觸發該方法)
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation ; 顯示區域發生改變後觸發
- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView; 地圖載入完成後觸發
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation; 顯示大頭針時觸發,返回大頭針檢視,通常自定義大頭針可以通過此方法進行
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view  點選選中某個大頭針時觸發
- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view 取消選中大頭針時觸發
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay 渲染地圖覆蓋物時觸發

使用者位置跟蹤

在很多帶有地圖的應用中預設開啟地圖都會顯示使用者當前位置,同時將當前位置標記出來放到螢幕中點方便使用者對周圍情況進行檢視。如果在iOS6或者iOS7中實現這個功能只需要新增地圖控制元件、設定使用者跟蹤模式、在-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation代理方法中設定地圖中心區域及顯示範圍。但是在iOS8中用法稍有不同:

1.由於在地圖中進行使用者位置跟蹤需要使用定位功能,而定位功能在iOS8中設計發生了變化,因此必須按照前面定位章節中提到的內容進行配置和請求。

2.iOS8中不需要進行中心點的指定,預設會將當前位置設定中心點並自動設定顯示區域範圍。

瞭解以上兩點,要進行使用者位置跟蹤其實就相當簡單了,值得一提的是-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation這個代理方法。這個方法只有在定位(利用前面章節中的定位內容)到當前位置之後就會呼叫,以後每當使用者位置發生改變就會觸發,呼叫頻率相當頻繁。

大頭針

在iOS開發中經常會標記某個位置,需要使用地圖標註,也就是大家俗稱的“大頭針”。只要一個NSObject類實現MKAnnotation協議就可以作為一個大頭針,通常會重寫協議中coordinate(標記位置)、title(標題)、subtitle(子標題)三個屬性,然後在程式中建立大頭針物件並呼叫addAnnotation:方法新增大頭針即可(之所以iOS沒有定義一個基類實現這個協議供開發者使用,多數原因應該是MKAnnotation是一個模型物件,對於多數應用模型會稍有不同,例如後面的內容中會給大頭針模型物件新增其他屬性)。

KCAnnotation.h

//
//  KCAnnotation.h
//  MapKit
//
//  Created by Kenshin Cui on 14/3/27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface KCAnnotation : NSObject<MKAnnotation>

@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;

@end

KCMainViewController.m

//
//  KCMainViewController.m
//  MapKit Annotation
//
//  Created by Kenshin Cui on 14/3/27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//  37.785834   -122.406417
//  39.92 116.39

#import "KCMainViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "KCAnnotation.h"

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

@end

@implementation KCMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initGUI];
}

#pragma mark 新增地圖控制元件
-(void)initGUI{
    CGRect rect=[UIScreen mainScreen].bounds;
    _mapView=[[MKMapView alloc]initWithFrame:rect];
    [self.view addSubview:_mapView];
    //設定代理
    _mapView.delegate=self;
    
    //請求定位服務
    _locationManager=[[CLLocationManager alloc]init];
    if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse){
        [_locationManager requestWhenInUseAuthorization];
    }
    
    //使用者位置追蹤(使用者位置追蹤用於標記使用者當前位置,此時會呼叫定位服務)
    _mapView.userTrackingMode=MKUserTrackingModeFollow;
    
    //設定地圖型別
    _mapView.mapType=MKMapTypeStandard;
    
    //新增大頭針
    [self addAnnotation];
}

#pragma mark 新增大頭針 
-(void)addAnnotation{
    CLLocationCoordinate2D location1=CLLocationCoordinate2DMake(39.95, 116.35);
    KCAnnotation *annotation1=[[KCAnnotation alloc]init];
    [email protected]"CMJ Studio";
    [email protected]"Kenshin Cui's Studios";
    annotation1.coordinate=location1;
    [_mapView addAnnotation:annotation1];
    
    CLLocationCoordinate2D location2=CLLocationCoordinate2DMake(39.87, 116.35);
    KCAnnotation *annotation2=[[KCAnnotation alloc]init];
    [email protected]"Kenshin&Kaoru";
    [email protected]"Kenshin Cui's Home";
    annotation2.coordinate=location2;
    [_mapView addAnnotation:annotation2];
}

#pragma mark - 地圖控制元件代理方法
#pragma mark 更新使用者位置,只要使用者改變則呼叫此方法(包括第一次定位到使用者位置)
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
    NSLog(@"%@",userLocation);
    //設定地圖顯示範圍(如果不進行區域設定會自動顯示區域範圍並指定當前使用者位置為地圖中心點)
    //    MKCoordinateSpan span=MKCoordinateSpanMake(0.01, 0.01);
    //    MKCoordinateRegion region=MKCoordinateRegionMake(userLocation.location.coordinate, span);
    //    [_mapView setRegion:region animated:true];
}

@end

執行效果:

MapKit_Annotation 

設定大頭針檢視

在一些應用中系統預設的大頭針樣式可能無法滿足實際的需求,此時就需要修改大頭針檢視預設樣式。根據前面MapKit的代理方法不難發現- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation;方法可以返回一個大頭針檢視,只要實現這個方法並在這個方法中定義一個大頭針檢視MKAnnotationView物件並設定相關屬性就可以改變預設大頭針的樣式。MKAnnotationView常用屬性:

屬性 說明
annotation 大頭針模型資訊,包括標題、子標題、地理位置。
image 大頭針圖片
canShowCallout 點選大頭針是否顯示標題、子標題內容等,注意如果在- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation;方法中重新定義大頭針預設情況是無法互動的需要設定為true。
calloutOffset 點選大頭針時彈出詳情資訊檢視的偏移量
selected 是否被選中狀態
leftCalloutAccessoryView 彈出詳情左側檢視
rightCalloutAccessoryView 彈出詳情右側檢視

需要注意:

a.這個代理方法的呼叫時機:每當有大頭針顯示到系統可視介面中時就會呼叫此方法返回一個大頭針檢視放到介面中,同時當前系統位置標註(也就是地圖中藍色的位置點)也是一個大頭針,也會呼叫此方法,因此處理大頭針檢視時需要區別對待。

b.類似於UITableView的代理方法,此方法呼叫頻繁,開發過程中需要重複利用MapKit的快取池將大頭針檢視快取起來重複利用。

c.自定義大頭針預設情況下不允許互動,如果互動需要設定canShowCallout=true

d.如果代理方法返回nil則會使用預設大頭針檢視,需要根據情況設定。

下面以一個示例進行大頭針檢視設定,這裡設定了大頭針的圖片、彈出檢視、偏移量等資訊。

KCAnnotation.h

//
//  KCAnnotation.h
//  MapKit
//
//  Created by Kenshin Cui on 14/3/27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface KCAnnotation : NSObject<MKAnnotation>

@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;

#pragma mark 自定義一個圖片屬性在建立大頭針檢視時使用
@property (nonatomic,strong) UIImage *image;

@end

KCMainViewController.m

//
//  KCMainViewController.m
//  MapKit Annotation
//
//  Created by Kenshin Cui on 14/3/27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//  37.785834   -122.406417
//  39.92 116.39

#import "KCMainViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "KCAnnotation.h"

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

@end

@implementation KCMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initGUI];
}

#pragma mark 新增地圖控制元件
-(void)initGUI{
    CGRect rect=[UIScreen mainScreen].bounds;
    _mapView=[[MKMapView alloc]initWithFrame:rect];
    [self.view addSubview:_mapView];
    //設定代理
    _mapView.delegate=self;
    
    //請求定位服務
    _locationManager=[[CLLocationManager alloc]init];
    if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse){
        [_locationManager requestWhenInUseAuthorization];
    }
    
    //使用者位置追蹤(使用者位置追蹤用於標記使用者當前位置,此時會呼叫定位服務)
    _mapView.userTrackingMode=MKUserTrackingModeFollow;
    
    //設定地圖型別
    _mapView.mapType=MKMapTypeStandard;
    
    //新增大頭針
    [self addAnnotation];
}

#pragma mark 新增大頭針 
-(void)addAnnotation{
    CLLocationCoordinate2D location1=CLLocationCoordinate2DMake(39.95, 116.35);
    KCAnnotation *annotation1=[[KCAnnotation alloc]init];
    [email protected]"CMJ Studio";
    [email protected]"Kenshin Cui's Studios";
    annotation1.coordinate=location1;
    annotation1.image=[UIImage imageNamed:@"icon_pin_floating.png"];
    [_mapView addAnnotation:annotation1];
    
    CLLocationCoordinate2D location2=CLLocationCoordinate2DMake(39.87, 116.35);
    KCAnnotation *annotation2=[[KCAnnotation alloc]init];
    [email protected]"Kenshin&Kaoru";
    [email protected]"Kenshin Cui's Home";
    annotation2.coordinate=location2;
    annotation2.image=[UIImage imageNamed:@"icon_paopao_waterdrop_streetscape.png"];
    [_mapView addAnnotation:annotation2];
}

#pragma mark - 地圖控制元件代理方法
#pragma mark 顯示大頭針時呼叫,注意方法中的annotation引數是即將顯示的大頭針物件
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //由於當前位置的標註也是一個大頭針,所以此時需要判斷,此代理方法返回nil使用預設大頭針檢視
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
        static NSString *[email protected]"AnnotationKey1";
        MKAnnotationView *annotationView=[_mapView dequeueReusableAnnotationViewWithIdentifier:key1];
        //如果快取池中不存在則新建
        if (!annotationView) {
            annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
            annotationView.canShowCallout=true;//允許互動點選
            annotationView.calloutOffset=CGPointMake(0, 1);//定義詳情檢視偏移量
            annotationView.leftCalloutAccessoryView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_classify_cafe.png"]];//定義詳情左側檢視
        }

        //修改大頭針檢視
        //重新設定此類大頭針檢視的大頭針模型(因為有可能是從快取池中取出來的,位置是放到快取池時的位置)
        annotationView.annotation=annotation;
        annotationView.image=((KCAnnotation *)annotation).image;//設定大頭針檢視的圖片
        
        return annotationView;
    }else {
        return nil;
    }
}
@end

執行效果:

MapKit_CustomeAnnotationImage

注意:

在MapKit框架中除了MKAnnotationView之外還有一個MKPinAnnotationView,它是MKAnnotationView的子類,相比MKAnnotationView多了兩個屬性pinColor和animationDrop,分別用於設定大頭針檢視顏色和新增大頭針動畫。

擴充套件--自定義大頭針彈詳情檢視

通過上面的示例不難看出MKAnnotationView足夠強大(何況還有MKPinAnnotationView),很多資訊都可以進行設定,但是唯獨不能修改大頭針描述詳情檢視(僅僅支援詳情中左右檢視內容)。要實現這個需求目前開發中普遍採用的思路就是:

a.點選一個大頭針A時重新在A的座標處新增另一個大頭針B(注意此時將A對應的大頭針檢視canShowCallout設定為false)作為大頭針詳情模型,然後在- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation;代理方法中判斷大頭針型別,如果是B則重寫MKAnnotationView(可以自定義一個類C繼承於MKAnnotationView),返回自定義大頭針檢視C。

b.定義大頭針檢視C繼承於MKAnnotationView(或者MKPinAnnotationView),在自定義大頭針檢視中新增自己的控制元件,完成自定義佈局。

在使用百度地圖客戶端時當點選一個搜尋位置時可以看到此位置的評價等資訊,檢視效果大概如下:

Baidu_CalloutView 

下面不妨試著實現一下這個效果:

大頭針模型:KCAnnotation.h

//
//  KCAnnotation.h
//  MapKit
//
//  Created by Kenshin Cui on 14/3/27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface KCAnnotation : NSObject<MKAnnotation>

@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;

#pragma mark 自定義一個圖片屬性在建立大頭針檢視時使用
@property (nonatomic,strong) UIImage *image;

#pragma mark 大頭針詳情左側圖示
@property (nonatomic,strong) UIImage *icon;
#pragma mark 大頭針詳情描述 
@property (nonatomic,copy) NSString *detail;
#pragma mark 大頭針右下方星級評價
@property (nonatomic,strong) UIImage *rate;

@end

彈出詳情大頭針模型:KCCalloutAnnotation.h

//
//  KCCalloutAnnotation.h
//  MapKit
//
//  Created by Kenshin Cui on 14/3/27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface KCCalloutAnnotation : NSObject<MKAnnotation>

@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy,readonly) NSString *title;
@property (nonatomic, copy,readonly) NSString *subtitle;

#pragma mark 左側圖示
@property (nonatomic,strong) UIImage *icon;
#pragma mark 詳情描述
@property (nonatomic,copy) NSString *detail;
#pragma mark 星級評價
@property (nonatomic,strong) UIImage *rate;

@end

彈出詳情大頭針檢視:KCCalloutAnnotatonView.h

//
//  KCCalloutView.h
//  MapKit
//
//  Created by Kenshin Cui on 14/3/27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//  自定義彈出標註檢視

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "KCCalloutAnnotation.h"

@interface KCCalloutAnnotationView : MKAnnotationView

@property (nonatomic ,strong) KCCalloutAnnotation *annotation;

#pragma mark 從快取取出標註檢視
+(instancetype)calloutViewWithMapView:(MKMapView *)mapView;

@end

KCCalloutAnnotationView.m

//
//  KCCalloutView.m
//  MapKit
//
//  Created by Kenshin Cui on 14/3/27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//

#import "KCCalloutAnnotationView.h"
#define kSpacing 5
#define kDetailFontSize 12
#define kViewOffset 80

@interface KCCalloutAnnotationView(){
    UIView *_backgroundView;
    UIImageView *_iconView;
    UILabel *_detailLabel;
    UIImageView *_rateView;
}

@end

@implementation KCCalloutAnnotationView

-(instancetype)init{
    if(self=[super init]){
        [self layoutUI];
    }
    return self;
}
-(instancetype)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
        [self layoutUI];
    }
    return self;
}

-(void)layoutUI{
    //背景
    _backgroundView=[[UIView alloc]init];
    _backgroundView.backgroundColor=[UIColor whiteColor];
    //左側新增圖示
    _iconView=[[UIImageView alloc]init];
    
    //上方詳情
    _detailLabel=[[UILabel alloc]init];
    _detailLabel.lineBreakMode=NSLineBreakByWordWrapping;
    //[_text sizeToFit];
    _detailLabel.font=[UIFont systemFontOfSize:kDetailFontSize];
    
    //下方星級
    _rateView=[[UIImageView alloc]init];
    
    [self addSubview:_backgroundView];
    [self addSubview:_iconView];
    [self addSubview:_detailLabel];
    [self addSubview:_rateView];
}

+(instancetype)calloutViewWithMapView:(MKMapView *)mapView{
    static NSString *[email protected]"calloutKey1";
    KCCalloutAnnotationView *calloutView=(KCCalloutAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:calloutKey];
    if (!calloutView) {
        calloutView=[[KCCalloutAnnotationView alloc]init];
    }
    return calloutView;
}

#pragma mark 當給大頭針檢視設定大頭針模型時可以在此處根據模型設定檢視內容
-(void)setAnnotation:(KCCalloutAnnotation *)annotation{
    [super setAnnotation:annotation];
    //根據模型調整佈局
    _iconView.image=annotation.icon;
    _iconView.frame=CGRectMake(kSpacing, kSpacing, annotation.icon.size.width, annotation.icon.size.height);
    
    _detailLabel.text=annotation.detail;
    float detailWidth=150.0;
    CGSize detailSize= [annotation.detail boundingRectWithSize:CGSizeMake(detailWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kDetailFontSize]} context:nil].size;
    float detailX=CGRectGetMaxX(_iconView.frame)+kSpacing;
    _detailLabel.frame=CGRectMake(detailX, kSpacing, detailSize.width, detailSize.height);
    _rateView.image=annotation.rate;
    _rateView.frame=CGRectMake(detailX, CGRectGetMaxY(_detailLabel.frame)+kSpacing, annotation.rate.size.width, annotation.rate.size.height);
    
    float backgroundWidth=CGRectGetMaxX(_detailLabel.frame)+kSpacing;
    float backgroundHeight=_iconView.frame.size.height+2*kSpacing;
    _backgroundView.frame=CGRectMake(0, 0, backgroundWidth, backgroundHeight);
    self.bounds=CGRectMake(0, 0, backgroundWidth, backgroundHeight+kViewOffset);
    
}
@end

主檢視控制器:KCMainViewController.m

//
//  KCMainViewController.m
//  MapKit Annotation
//
//  Created by Kenshin Cui on 14/3/27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//  37.785834   -122.406417
//  39.92 116.39

#import "KCMainViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "K