[Xcode]How to slide the map to the tapped position in MKMapView

Screenshot 2014 02 08 19 05 47

Good evening, this is Bono.

I was making a map app and felt like I would use it in the future, so I made a note of it.

When you want to slide the map to the tapped position in MKMapView

Basically, the following flow.

  • Register gesture events
  • Tap is detected
  • Get tapped coordinates
  • Animated slide to those coordinates

code

#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];
}