MapPin.h :
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface MapPin : NSObject<MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subtitle;
}
@property (nonatomic,readwrite,assign)CLLocationCoordinate2D coordinate;
- (id)initWithCoordinates:(CLLocationCoordinate2D)location placeName:(NSString *)placeName description:(NSString *)description;
-(void)setCoordinate:(CLLocationCoordinate2D)newCoordinate;
@end
そしてこれが MapPin.m です
#import "MapPin.h"
@implementation MapPin
@synthesize coordinate;
-(NSString *)subtitle{
return nil;
}
-(NSString *)title{
return nil;
}
-(id)initWithCoordinates:(CLLocationCoordinate2D)location placeName:(NSString *)placeName description:(NSString *)description{
coordinate=location;
return self;
}
-(CLLocationCoordinate2D)location{
return coordinate;
}
-(void)setCoordinate:(CLLocationCoordinate2D)newCoordinate{
coordinate=newCoordinate;
}
@end
ViewController.h では、MKMapViewDelegate プロトコルを採用しました。そしてここに ViewController.m があります:
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
MKPinAnnotationView *pin = (MKPinAnnotationView *)[self.MyMap dequeueReusableAnnotationViewWithIdentifier:@"myPin"];
if(pin == nil){
pin=[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"myPin"];
}
else{
pin.annotation=annotation;
}
pin.draggable=YES;
return pin;
}
//Add Location button
- (IBAction)AddPin:(id)sender {
CLLocationCoordinate2D center;
center.latitude=Locate.location.coordinate.latitude;
center.longitude=Locate.location.coordinate.longitude;
MKCoordinateRegion region;
region.center=center;
region.span.latitudeDelta=0.2f;
region.span.longitudeDelta=0.2f;
MapPin *myPin = [[MapPin alloc]initWithCoordinates:self.MyMap.centerCoordinate placeName:@"LoMinder!" description:@"Set Location for LoMinder!"];
[_MyMap addAnnotation:myPin];
}
//Dropping the pin:
- (void)mapView:(MKMapView *)mapView
annotationView:(MKAnnotationView *)annotationView
didChangeDragState:(MKAnnotationViewDragState)newState
fromOldState:(MKAnnotationViewDragState)oldState
{
//Region
MKCoordinateRegion myRegion;
//Center
CLLocationCoordinate2D center;
if (newState == MKAnnotationViewDragStateStarting)
{
[_MyMap setRegion:myRegion animated:YES];
}
if(newState == MKAnnotationViewDragStateDragging)
{
myRegion.center=annotationView.annotation.coordinate;
myRegion.span.latitudeDelta=0.2f;
myRegion.span.longitudeDelta=0.2f;
[_MyMap setRegion:myRegion animated:YES];
}
if(newState==MKAnnotationViewDragStateEnding)
{
arrived=self.MyMap.centerCoordinate;
center=annotationView.annotation.coordinate;
myRegion.center=center;
myRegion.span.latitudeDelta=0.2f;
myRegion.span.longitudeDelta=0.2f;
[_MyMap setRegion:myRegion animated:YES];
}
}
///// MapPin.h も ViewController にインポートしました。アプリを実行すると、注釈ピンを取得するために [場所の追加] ボタンを押す必要があります。ボタンを押すと、注釈ピンがマップに表示されますが、問題は、ドラッグしようとすると、ドラッグ不可にします。助けてください。ありがとうございました :)