[Xcode]MKMapViewでタップされた位置に地図をスライドする方法

スクリーンショット 2014 02 08 19 05 47

こんばんは、ボーノです。

地図アプリを作ってて、今後も使う気がしたのでメモメモ。

MKMapViewでタップされた位置に地図をスライドしたい時

基本的には下記流れ。

  • ジェスチャーイベントを登録
  • タップを検知
  • タップされた座標を取得
  • その座標までアニメーションでスライド

コード

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController {
    MKMapView *mapView;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

        // Custom initialization
        CGRect disp = [[UIScreen mainScreen] bounds];

        //mapViewの生成
        mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, disp.size.width, disp.size.height)];
        [self.view addSubview:mapView];

        mapView.delegate = self;
        MKCoordinateRegion region = mapView.region;
        region.span.latitudeDelta = 0.05;
        region.span.longitudeDelta = 0.05;
        region.center = CLLocationCoordinate2DMake(35.658517, 139.701334);
        [mapView setRegion:region animated:YES];

        //ジェスチャーの登録
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(mapTapped:)];
        [mapView addGestureRecognizer:tapGesture];
    }
}

//タップされた時の動作
- (void)mapTapped:(UITapGestureRecognizer *)sender
{
    CGPoint location = [sender locationInView:mapView];
    CLLocationCoordinate2D mapPoint = [mapView convertPoint:location toCoordinateFromView:mapView];

    //アニメーションで移動
    [mapView setCenterCoordinate:mapPoint animated:YES];
}