2012年5月29日火曜日

MapKitサンプル1 - 地図の表示と操作

前回の「CoreLocationサンプル3 - ジオコーディング」に続いて、今回は地図の表示と操作です。
やはり緯度・経度の座標情報には、地図がなければ分かりづらいです。

iOS Developer Libraryの「位置情報対応プログラミングガイド」(英語版はMaking Your Application Location-Aware)に沿って、サンプルを公開します。


注意点

MapKitでは、Googleマップを利用しています。そのため、Googleマップの利用規約に従う必要があります。
詳細は、Googleマップの利用規約(Google Maps Terms of Service)(全文)をご覧ください。


実装手順

地図の表示

  • 「MapKit.framework」「CoreLocation.framework」の追加
    1. 単に地図を表示するだけならCoreLocationは不要ですが、様々な処理をするのに必要となります。
  • ヘッダのインポート
    #import <MapKit/MapKit.h>
    #import <CoreLocation/CoreLocation.h>
  • (必要ならば)プロトコルの宣言
    @interface ViewController : UIViewController <MKMapViewDelegate>
    @end
  • MKMapViewの作成
    1. InterfaceBuilderで追加するか、以下のようにして作成します
    - (void)viewDidLoad
    {
        // 画面全体に表示
        MKMapView *mapView = [[[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)] autorelease];
        [self.view addSubview:mapView];
        
        // ユーザの現在位置を表示
        _mapView.showsUserLocation = YES;
        
        // 地図の種類をハイブリッドにする
        _mapView.mapType = MKMapTypeHybrid;
        
        // デバイスの向きに合わせて地図を回転
        [_mapView setUserTrackingMode:MKUserTrackingModeFollowWithHeading animated:YES];
    }


3種類の座標

MKMapKitでは、以下の3種類の座標情報を扱い、地図を表示したり、各種操作をしたりします。
  • 地図座標(Map coordinates)
    • CoreLocationでも扱った「緯度・経度」の情報です。「-90 <= 緯度 <= +90」「-180 <= 経度 <= +180」となります。
  • 地図点(Map points)
    • 「地図座標」と同様ですが、地図をx,yの座標で管理します。「0.0 <= x <= 268435456.0」「0.0 <= y <= 268435456.0」となります。
  • 点(Points)
    • 地図全体に付けられているものではなく、デバイスのMKMapViewに対しての座標です。「0 < x < 320」「0 < y < 460」となり、画面にはどこの場所の地図が表示されているかなどをしてしています。

それぞれの座標は相互に変換することができ、変換方法は下記のとおりです。
変換元変換先変換方法
地図座標- (CGPoint)convertCoordinate:(CLLocationCoordinate2D)coordinate toPointToView:(UIView *)view
- (CGRect)convertRegion:(MKCoordinateRegion)region toRectToView:(UIView *)view
地図座標地図点MKMapPoint MKMapPointForCoordinate(
CLLocationCoordinate2D coordinate
);
地図点地図座標CLLocationCoordinate2D MKCoordinateForMapPoint(
MKMapPoint mapPoint
);
MKCoordinateRegion MKCoordinateRegionForMapRect(
MKMapRect rect
);
地図点- (CGPoint)pointForMapPoint:(MKMapPoint)mapPoint
- (CGRect)rectForMapRect:(MKMapRect)mapRect
地図座標- (CLLocationCoordinate2D)convertPoint:(CGPoint)point toCoordinateFromView:(UIView *)view
- (MKCoordinateRegion)convertRect:(CGRect)rect toRegionFromView:(UIView *)view
地図点- (MKMapPoint)mapPointForPoint:(CGPoint)point
- (MKMapRect)mapRectForRect:(CGRect)rect

その他、プロパティや有用なメソッドが多いため、徐々に追記します。

サンプル

ソースコードはGitHubにて公開しています。
iOS-SampleCodes/MapKitSample-MapView - GitHub



次回

次回は、「MapViewサンプル2 - 注釈の表示」です。

0 コメント:

コメントを投稿