Part one of this section on MapKits showed how to embed a map and place a floating toolbar for switching the map views, however it didn’t cover how to drop the pin where you wanted it.

Create the Object
First lets create a new NSObject for the place mark. Let’s call it ‘PlaceMark’
PlaceMark.h
#import <Foundation/Foundation.h> #import <MapKit/MapKit.h> @interface PlaceMark : NSObject{ CLLocationCoordinate2D coordinate; NSString *subtitletext; NSString *titletext; } @property (nonatomic, readonly) CLLocationCoordinate2D coordinate; @property (readwrite, retain) NSString *titletext; @property (readwrite, retain) NSString *subtitletext; -(id)initWithCoordinate:(CLLocationCoordinate2D) coordinate; - (NSString *)subtitle; - (NSString *)title; -(void)setTitle:(NSString*)strTitle; -(void)setSubTitle:(NSString*)strSubTitle; @end
PlaceMark.m
#import "PlaceMark.h"
@implementation PlaceMark
@synthesize coordinate, titletext, subtitletext;
- (NSString *)subtitle{
return subtitletext;
}
- (NSString *)title{
return titletext;
}
-(void)setTitle:(NSString*)strTitle {
self.titletext = strTitle;
}
-(void)setSubTitle:(NSString*)strSubTitle {
self.subtitletext = strSubTitle;
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
coordinate=c;
return self;
}
@end
Adding a pin to your map
Firstly remember to add
#import "PlaceMark.h"
To your map controller, from the previous example inside the displayMap function under the region.center call
PlaceMark *addAnnotation = [[[PlaceMark alloc] initWithCoordinate:location] retain]; [addAnnotation setTitle:@"The Pin Title"]; [addAnnotation setSubTitle:@"The pin subtitle goes here"]; [mapView addAnnotation:addAnnotation];
Then create the following delegate method
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MyPin"];
annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
[annView setSelected:YES];
annView.pinColor = MKPinAnnotationColorPurple;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
Voila you now have a pin dropped on the map and automatically selected. If you don’t want the title automatically displayed then change
[annView setSelected:YES];
The final part demonstrates how to create a mini map


Trackbacks /
Pingbacks