Displaying Pin with Title (annotation) once map loads

别来无恙 提交于 2019-11-30 13:55:14
nehal

For that you need to create annotation create one class which has CLLocationCoordinate2D,title,subtitle like this .h file

#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>


@interface DisplayMap : NSObject <MKAnnotation> {

    CLLocationCoordinate2D coordinate; 
    NSString *title; 
    NSString *subtitle;
}
@property (nonatomic, assign) CLLocationCoordinate2D coordinate; 
@property (nonatomic, copy) NSString *title; 
@property (nonatomic, copy) NSString *subtitle;

@end

and .m file

#import "DisplayMap.h"


@implementation DisplayMap

@synthesize coordinate,title,subtitle;


-(void)dealloc{
    [title release];
    [super dealloc];
}

@end

and then add following code to viewdidload

DisplayMap *ann = [[DisplayMap alloc] init]; 
ann.title=@"put title here";
ann.coordinate = region.center; 
[mapView addAnnotation:ann];

and implement following method

-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:
(id <MKAnnotation>)annotation {
    MKPinAnnotationView *pinView = nil; 
    if(annotation != mapView.userLocation) 
    {
        static NSString *defaultPinID = @"com.invasivecode.pin";
        pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
        if ( pinView == nil ) pinView = [[[MKPinAnnotationView alloc]
                                          initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];

        pinView.pinColor = MKPinAnnotationColorPurple; 
        pinView.canShowCallout = YES;
        pinView.animatesDrop = YES;
    } 
    else {
        [mapView.userLocation setTitle:@"I am here"];
    }
    return pinView;
}

Follow this tutorial:code with explanation is given:

You need to create a "map annotation" object - which can actually be any object, but it must conform to MKAnnotation protocol (so you can basically declare your object as

@interface MyAnnotation: NSObject<MKAnnotation>

). Check out that protocol in the manual, it is just 3 method and one property (coordinate). Set the coordinate and title, and then add the annotation to the mapView ([self.mapView addAnnotation:annotation])

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!