iPhone日本の城

江戸城、名古屋城、安土城をマップ上で探すようなiPhoneアプリのサンプルコードを描いてみます。

使った画像


動かすとこんな感じです

サンプルコード

#import “ViewController.h”

#import <MapKit/MapKit.h>

@interface ViewController ()

@property (nonatomic, weak) MKMapView *mapView;

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    

    [self createMap];

    

    [self createButtons];

}

– (void)createMap

{

    MKMapView *mv = [[MKMapView alloc] initWithFrame:self.view.bounds];

    [self.view addSubview:mv];

    self.mapView = mv;

}

#define CastleNames @[@“Edo”, @“Nagoya”, @“Azuchi”]

– (void)createButtons

{

    UIView *pan = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view.bounds) – 100, 320, 100)];

    pan.backgroundColor = [[UIColor greenColor] colorWithAlphaComponent:0.7];

    [self.view addSubview:pan];

    

    for (int i=0; i<3; i++) {

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

        btn.tag = i;

        [btn setImage:[UIImage imageNamed:@”siro”] forState:UIControlStateNormal];

        [btn sizeToFit];

        float x = (320.0 / 3.0) * (i + 0.5);

        float y = 50;

        btn.center = CGPointMake(x, y);

        [pan addSubview:btn];

        

        UILabel *l = [[UILabel alloc] init];

        l.text = CastleNames[i];

        [l sizeToFit];

        l.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];

        [btn addSubview:l];

        

        [btn addTarget:self action:@selector(search:) forControlEvents:UIControlEventTouchUpInside];

    }

}

– (void)search:(UIButton*)btn

{

    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];

    request.naturalLanguageQuery = [NSString stringWithFormat:@”%@ Castle”, CastleNames[btn.tag]];

    MKLocalSearch *search = [[MKLocalSearch alloc] initWithRequest:request];

    [search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError

                                         *error) {

        NSMutableArray *placemarks = [NSMutableArray array];

        for (MKMapItem *item in response.mapItems) {

            [placemarks addObject:item.placemark];

        }

        

        [self.mapView removeAnnotations:[self.mapView annotations]];

        [self.mapView showAnnotations:placemarks animated:YES];

    }];

    

    [self performSelector:@selector(zoomout:) withObject:@(0.1) afterDelay:2.0];

}

– (void)zoomout:(NSNumber*)level

{

    MKCoordinateRegion region = self.mapView.region;

    region.span = MKCoordinateSpanMake([level floatValue], [level floatValue]);

    [self.mapView setRegion:region animated:YES];

    

    if (level.intValue < 5) {

        float next = [level floatValue] + 0.4;

        [self performSelector:@selector(zoomout:) withObject:@(next) afterDelay:0.4];

    }

}

@end