Displaying Pin with Title (annotation) once map loads

后端 未结 2 507
无人及你
无人及你 2021-01-02 16:23

I am working on my first app and within it I\'m just trying to have on button click show a map with a pin (and title on this pin of location). I was able to load the mapview

相关标签:
2条回答
  • 2021-01-02 16:52

    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:

    0 讨论(0)
  • 2021-01-02 17:05

    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])

    0 讨论(0)
提交回复
热议问题