2012-03-09 83 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

相關問題