MKMapViewで2点間をanimationで移動させてみた。

(XcodeのiOS6 Simulatorで試しています。)

ポイント

・MKAnnotationでピンを作成

・NewYork Tokyo間をタイマーで移動させる

・移動中のマップ描画が消えてしまった。さきに表示しておくにはどうするのか。

(そのうちわかるといいな。)

サンプルコード

#import “ViewController.h”

#import <MapKit/MapKit.h>

@interface MyAnnotation : NSObject<MKAnnotation> {

CLLocationCoordinate2D coordinate;

}

@end

@implementation MyAnnotation

@synthesize coordinate;

– (NSString *)subtitle{

return nil;

}

– (NSString *)title{

return nil;

}

-(id)initWithCoordinate:(CLLocationCoordinate2D) c{

coordinate=c;

return self;

}

@end

@interface ViewController () <MKMapViewDelegate> {

    CLLocationCoordinate2D newYorkCoord;

    CLLocationCoordinate2D tokyoCoord;

    MKMapView *mapView;

}

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

}

– (void)viewDidAppear:(BOOL)animated

{

    mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 520)];

    mapView.center = self.view.center;

    [self.view addSubview:mapView];

    mapView.showsUserLocation = YES;

    

    // 4秒後

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 4 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{

        [self moveNewYork];

    });

    

    // 5秒後

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{

        [self pinNewYork];

    });

    

    // 7秒後

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 7 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{

        [self moveTokyo];

    });

    // 9秒後

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 9 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{

        [self pinTokyo];

    });

}

– (void)moveNewYork

{

    // New York

    newYorkCoord.latitude = 40.707560;

    newYorkCoord.longitude = –73.800000;

    [mapView setCenterCoordinate:newYorkCoord animated:YES];

}

– (void)pinNewYork

{

    MyAnnotation *annotation = [[MyAnnotation alloc] initWithCoordinate:newYorkCoord];

    [mapView addAnnotation:annotation];

}

– (void)moveTokyo

{

    // Tokyo

    tokyoCoord.latitude = 35.603719;

    tokyoCoord.longitude = 139.658203;

    

    

    [mapView setCenterCoordinate:tokyoCoord animated:YES];

}

– (void)pinTokyo

{

    MyAnnotation *annotation = [[MyAnnotation alloc] initWithCoordinate:tokyoCoord];

    [mapView addAnnotation:annotation];

}

// タッチしたところの座標を取得

// デバック用

– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    UITouch *t = [touches anyObject];

    CGPoint point = [t locationInView:mapView];

    CLLocationCoordinate2D coord= [mapView convertPoint:point toCoordinateFromView:mapView];

    NSLog(@”lat  %f”,coord.latitude);

    NSLog(@”long %f”,coord.longitude);

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end