iOS开发——地图标记物根据数据变化

作者: kuai空调 | 来源:发表于2016-04-28 15:57 被阅读163次

在进行地图应用开发的时候经常使用图片自定义标记物。但是如果有这样的需求:根据服务器返回数据的时间距当前时间的远近展示不同透明度的标记物,该怎么办呢?

我是这样实现的。首先要实现自定义的annotation,应该先创建一个遵守<MKAnnotation>的类,头文件应该是这样的:

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

@interface HZYAnnotation : NSObject<MKAnnotation>
@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@end

为了实现我们的需求,现在给这个类添加一个属性,用来记录标记物的透明度

@property (nonatomic, assign) CGFloat alpha;

接下来,在mapView所在的控制器中实现MKMapView的这个代理方法

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(HZYAnnotation *)annotation{
    static NSString *ID = @"anno";
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    MKAnnotationView *annoView = [mapView dequeueReusableAnnotationViewWithIdentifier:ID];
    if (annoView == nil) {
        annoView = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:ID];
    }
    annoView.canShowCallout = YES;
    annoView.image = [[UIImage imageNamed:@"danger_dot"] imageByApplyingAlpha:annotation.alpha];
    return annoView;
}

亮点就在倒数第三行,annoView的image,通过annotation的alpha属性设置了透明度。为什么不直接设置annoView的alpha?因为这样做会导致Callout(就是点击标记物出现的小标签)的透明度一起变化。

最后,在添加标记物的方法中给annotation的alpha属性赋值就可以了,例如这样:

HZYAnnotation *annotation = [[HZYAnnotation alloc]init];
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(anno.latitude, anno.longitude);
annotation.coordinate = coordinate;
annotation.title = anno.addr;
annotation.subtitle = [self caculateHourBefore:anno.time];
annotation.alpha = 1 - (currentDate - anno.time) / (60 * 60 * 4.0);
[self.mapView addAnnotation:annotation];

扩展开来,通过这个思路,你可以为HZYAnnotion这个类添加任何属性,并据此来改变标记物的样式。

相关文章

网友评论

    本文标题:iOS开发——地图标记物根据数据变化

    本文链接:https://www.haomeiwen.com/subject/lsrhrttx.html