2012-03-09 75 views
5

我想将自定义图像添加到我在地图中的注释中。我已经做了以下的自定义MapAnnotationView:IOS:将图像添加到自定义MKAnnotationview

#import <UIKit/UIKit.h> 
#import <Foundation/Foundation.h> 
#import <MapKit/MapKit.h> 
#import <CoreLocation/CoreLocation.h> 
@class POI; 

@interface MapAnnotation : MKAnnotationView <MKAnnotation > 

@property (nonatomic) CGFloat lat; 
@property (nonatomic) CGFloat lon; 
@property (nonatomic) CGFloat altitude; 
@property (nonatomic, copy) NSString * title; 
@property (nonatomic, copy) NSString * subtitle; 
@property (nonatomic,retain) NSString *source; 
@property (nonatomic,retain) UIImage *image; 

@end 

@implementation MapAnnotation 
@synthesize coordinate; 
@synthesize lat=_lat,lon=_lon,altitude= _altitude; 
@synthesize subtitle= _subtitle, title= _title, source=_source, image =_img; 


- (CLLocationCoordinate2D)coordinate;{ 
    CLLocationCoordinate2D position; 
    if (_lat != 0.0 && _lon != 0.0) { 
     position.latitude = _lat; 
     position.longitude = _lon; 

    }else { 
     position.latitude=0.0; 
     position.longitude=0.0; 
    } 

    return position; 
} 

@end 

-(void) mapDataToMapAnnotations{ 

    NSMutableArray *toRemove = [NSMutableArray arrayWithCapacity:10]; 
    for (id annotation in _map.annotations) 
     if (annotation != _map.userLocation) 
      [toRemove addObject:annotation]; 
    [_map removeAnnotations:toRemove]; 

    [_data removeAllObjects]; 

    [_data addObjectsFromArray:[UDdelegate naturArray]]; 


    if(_data != nil){ 
     MapAnnotation * tmpPlace; 
     //for(NSDictionary * poi in _data){ 


     for(POI* poi in _data){ 

      tmpPlace = [[MapAnnotation alloc]init]; 

      tmpPlace.title = [poi title]; 
      tmpPlace.lat = [poi lat]; 
      tmpPlace.lon = [poi lon]; 
      tmpPlace.subtitle = [poi dist]; 
      tmpPlace.image = [poi poiIcon]; 

      [self.map addAnnotation:tmpPlace]; 
      [_map setNeedsLayout]; 
     } 
    } 
} 

的问题是,该引脚是标准redPin ....我相信图标不为空,已检查了这一点。

感谢

回答

11

你必须服务于MapKit委托方法mapView:viewForAnnotation:与自定义视图。

- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation 
{ 
    static NSString *annotationViewReuseIdentifier = @"annotationViewReuseIdentifier"; 

    MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewReuseIdentifier]; 

    if (annotationView == nil) 
    { 
     annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewReuseIdentifier] autorelease]; 
    } 

    annotationView.image = [UIImage imageNamed:@"pin_image.png"]; 
    annotationView.annotation = annotation; 

    return annotationView; 
} 

要封装更多,您应该像创建自定义注释视图一样创建自定义注释视图并为您的类提供上面的委托方法。

我建议您重命名MapAnnotation类,因为它很混乱。 iOS中还有Annotations是这些注释视图的数据持有者。为了解决这个问题,我宁愿编写继承类的类型,在这个例子中,你的自定义类的末尾是MKAnnotationView。例如CustomPinAnnotationView

+0

在我的情况下,上面的委托方法不会被调用,即使我已经添加了委托。 (并将其分配为,mapView.delegate = self;) – stack 2012-09-25 12:34:55

相关问题