これまで見てきたように、setShowsUserLocationフラグは、デフォルトの青いバブルを使用して現在の場所のみを表示します。
ここで行う必要があるのは、電話からの位置情報の更新をリッスンし、自分で注釈を手動で再配置することです。これを行うには、CLLocationManagerインスタンスを作成し、LocationManagerがデリゲートに更新を通知するたびにアノテーションを削除して置き換えます。
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
// update annotation position here
}
座標を再配置するために、プロトコルMKAnnotationに準拠するクラスPlacemarkがあります。
//--- .h ---
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface Placemark : NSObject <MKAnnotation> {
}
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, retain) NSString *strSubtitle;
@property (nonatomic, retain) NSString *strTitle;
-(id)initWithCoordinate:(CLLocationCoordinate2D) coordinate;
- (NSString *)subtitle;
- (NSString *)title;
@end
//--- .m ---
@implementation Placemark
@synthesize coordinate;
@synthesize strSubtitle;
@synthesize strTitle;
- (NSString *)subtitle{
return self.strSubtitle;
}
- (NSString *)title{
return self.strTitle;
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) c {
self.coordinate = c;
[super init];
return self;
}
@end
次に、mapviewコントローラーに次のように注釈を配置します。
- (void) setPlacemarkWithTitle:(NSString *) title andSubtitle:(NSString *) subtitle forLocation: (CLLocationCoordinate2D) location {
//remove pins already there...
NSArray *pins = [mapView annotations];
for (int i = 0; i<[pins count]; i++) {
[mapView removeAnnotation:[pins objectAtIndex:i]];
}
Placemark *placemark=[[Placemark alloc] initWithCoordinate:location];
placemark.strTitle = title;
placemark.strSubtitle = subtitle;
[mapView addAnnotation:placemark];
[self setSpan]; //a custom method that ensures the map is centered on the annotation
}