iOS高德地图自定义annotation添加不同图片

时间:2024-04-24 03:23:57

1.model类里面添加index

#import <MAMapKit/MAMapKit.h>

#import <AMapSearchKit/AMapCommonObj.h>

@interface POIAnnotation : NSObject <MAAnnotation>

- (id)initWithPOI:(AMapPOI *)poi;

@property (nonatomic, readonly, strong) AMapPOI *poi;

@property(assign,nonatomic)NSInteger idx;

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

/*!

@brief 获取annotation标题

@return 返回annotation的标题信息

*/

- (NSString *)title;

/*!

@brief 获取annotation副标题

@return 返回annotation的副标题信息

*/

- (NSString *)subtitle;

/*!

@brief 获取经纬度

@return 返回annotation的经纬度

*/

- (AMapGeoPoint *)location;

@end

2.给index赋值

/* POI 搜索回调. */

- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response

{

if (response.pois.count == 0)

{

return;

}

NSMutableArray *poiAnnotations = [NSMutableArray arrayWithCapacity:response.pois.count];

[response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {

POIAnnotation *annotation =[[POIAnnotation alloc] initWithPOI:obj];

annotation.idx = idx;

[poiAnnotations addObject:annotation];

}];

/* 将结果以annotation的形式加载到地图上. */

[self.mapView addAnnotations:poiAnnotations];

/* 如果只有一个结果,设置其为中心点. */

if (poiAnnotations.count == 1)

{

[self.mapView setCenterCoordinate:[poiAnnotations[0] coordinate]];

}

/* 如果有多个结果, 设置地图使所有的annotation都可见. */

else

{

[self.mapView showAnnotations:poiAnnotations animated:NO];

}

}

3.取值

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation

{

if ([annotation isKindOfClass:[POIAnnotation class]])

{

static NSString *poiIdentifier = @"poiIdentifier";

MAPinAnnotationView *poiAnnotationView = (MAPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:poiIdentifier];

if (poiAnnotationView == nil)

{

poiAnnotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:poiIdentifier];

}

poiAnnotationView.image = [UIImage imageNamed:[NSString stringWithFormat:@"poi_marker_%ld.png",((POIAnnotation*)annotation).idx]];

poiAnnotationView.canShowCallout = NO;

return poiAnnotationView;

}

return nil;

}