まだの方はまずそちらをお読みください。
今回はMKMapViewにPinをドロップします。
Tapでドロップ出来なかったので、LongTapへ逃げました。
そんなに操作性に不便はありません。
まずはヘッダーファイルから
MapViewController
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface MapViewController : UIViewController <MKAnnotation> {
MKMapView *mapView;
MKPointAnnotation *annotation;
}
@end
前回と違うのは、MKAnnotationが含まれている点です。MKPointAnnotationはPinのインスタンスです。
これを宣言しておいて、緯度、経度を保存します。
MapViewController.m
#import <MapKit/MapKit.h>
#import "MapViewController.h"
@implementation MapViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
// set map view
mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc]
initWithTarget:self
action:@selector(handleLongTap:)
];
recognizer.minimumPressDuration = .8;
[mapView addGestureRecognizer:recognizer];
recognizer = nil;
// declare annotation;
annotation = [[MKPointAnnotation alloc] init];
[self.view addSubview:mapView];
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)handleLongTap:(UILongPressGestureRecognizer *)recognizer {
if(recognizer.state == UIGestureRecognizerStateBegan){
CGPoint point = [recognizer locationInView:mapView];
// get coordinate point from map
CLLocationCoordinate2D coord = [mapView convertPoint:point toCoordinateFromView:mapView];
float latitude = coord.latitude;
float longitude = coord.longitude;
NSLog(@"%@:%f %@:%f", @"longitude:",longitude,@"latitude",latitude);
// set annotation
annotation.coordinate = coord;
[mapView addAnnotation:annotation];
}
return;
}
@end
これで、MKPointAnnotationをドロップできました!
わからない事があったら聞いてください。
1日以内に返事すると思います。
0 件のコメント:
コメントを投稿