地図上に現在地を表示する

Last-modified: 2012-08-17 (金) 09:11:04

Overview

  1. MKMapViewのインスタンスはCore Locationを使った現在位置の測定方法を知っている
    • MkMapViewのshowsUserLocationプロパティをYESにすると測定を行い、現在位置を地図上に表示する
  2. 地図に現在位置を表示できるようになるとMKMapViewはデリゲートにmapView:didUpdateUserLocation:メッセージを送信する.
    • このメッセージにはMKUserLocationインスタンスが含まれる.
  3. MKMapViewは"region"プロパティをもち,世界地図のどこを中心にどの範囲で表示するかを表すプロパティである.
    • MKMapViewに現在位置を表示するregionをセットしなおすと,地図の再描画が行われる.regionはMKCoodinateRegion型であり次の2つのメンバをもつ.
      • CLLocationCoordinate2D : 地図の中心を表す
      • MKCoordinateSpan : 中心から東西南北どの範囲で拡大/縮小するか(m単位).
    • MKMapViewにregionを使ってsetRegion:animated:メッセージを送信すると現在位置を拡大/縮小表示する.
  4. MKCoordinateRegionMakeWithDistanceを使うと,現在位置(CLLocationCoordinate)と表示範囲(MKCoordinateSpan)から
    regionプロパティを作成できる.

SampleCode

  • MymapAppDelegate.h

    #import <CoreLocation/CoreLocation.h>

    #import <MapKit/MapKit.h>

    @interface MymapAppDelegate * NSObject

        <UIApplicationDelegate, CLLocationManagerDelegate, MKMapViewDelegate>

    {

      CLLocationManager *locationManager;

      IBOutlet MKMapView *myMapView;

    }

    @prpperty (nonatomic, retain) IBOutlet UIWindow *window;

    @ end

  • MymapAppDelegate.m

    #import "MymapAppDelegate.h"

    - (BOOL)application:(UIApplication *)application

     didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    {

      locationManager = [[CLLocationManager alloc] init];

      [locationManager setDelegate:self];

      [locationManager setDistanceFilter:kCLDistanceFilterNone];

      [locationManager setDesiredAccuracy:kCLLocationAcuuracyBest];

      [myMapView setShowsUserLocation:YES];

      [[self window] makeKeyAndVisible];

      return YES;

    }

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

    {

      // 現在位置からcordinateプロパティを取得(getter経由)

      CLLocationCoordinate2D loc = [userLocation coordinate];

      // regionプロパティを作成

      MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 250, 250);

      // MKMapViewに現在位置表示用のregionをセット

      [myMapView setRegion:region animated:YES];

    }

    - (void)dealloc

    {

      if ([locationManager delegaet == self]) {

       [locationManager setDelegate:nil];

      }

      [locationManager release];

      [_window release];

      [super dealloc];