Skip to content

覆盖物 ​

本篇覆盖丰图地图 iOS SDK 提供的地图覆盖物类型及其用法。覆盖物分为两大类:注解类(Marker/自定义 Marker,通过 addAnnotation: 添加)和 Overlay 类(Polyline/MultiPolyline/Polygon/Circle/Arc,通过 addOverlay: 添加)。Overlay 类需要在 delegate 的 mapView:viewForOverlay: 中返回对应的 View 对象来设定样式。

官方 Demo 的 BaseMapViewController 基类提供 coordinateForCity: 获取深圳/北京/上海/广州坐标,下文示例中直接引用。覆盖物 View 的样式属性(颜色、线宽等)均在 viewForOverlay: 回调中设定,后续可通过持有的 View 引用动态更新。

Marker 点标记 ​

功能说明 ​

Marker 是使用频率最高的覆盖物。iOS SDK 采用注解(Annotation)+ 视图(AnnotationView)的模式:先创建注解对象携带坐标/标题/图标等数据,通过 addAnnotation: 添加到地图,然后在 delegate 的 viewForAnnotation: 回调中创建/复用视图并设置样式。支持默认水滴大头针、自定义图标、可拖拽、InfoWindow 等。

关键代码 ​

objc
// ── 创建注解并添加 ──
SFMPointAnnotation *a = [[SFMPointAnnotation alloc] init];
a.coordinate = CLLocationCoordinate2DMake(22.5429, 113.9414);
a.title = @"深圳顺丰总部";
a.subtitle = @"这是 snippet 描述";
[self.mapView addAnnotation:a];

// ── 自定义图标 Marker ──
// 将图标携带在注解上(可自定义子类或使用关联对象)
UIImage *icon = [self circleImageWithColor:[UIColor redColor] size:CGSizeMake(32, 32)];
SFMPointAnnotation *custom = [[SFMPointAnnotation alloc] init];
custom.coordinate = pos;
custom.title = @"自定义图标Marker";
[self.mapView addAnnotation:custom];

// ── 可拖拽 Marker ──
SFMPointAnnotation *draggable = [[SFMPointAnnotation alloc] init];
draggable.coordinate = pos;
draggable.title = @"可拖拽Marker";
[self.mapView addAnnotation:draggable];
// 在 viewForAnnotation: 中设置 view.draggable = YES

// ── delegate: 创建/复用视图 ──
- (SFMAnnotationView *)mapView:(SFMapView *)mapView
               viewForAnnotation:(id<SFMAnnotation>)annotation {
    // 有图标:使用 SFMAnnotationView + image
    static NSString *reuseId = @"marker";
    SFMAnnotationView *view = (SFMAnnotationView *)
        [mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
    if (!view) {
        view = [[SFMAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
    }
    view.annotation = annotation;
    view.image = icon;           // 自定义图标
    view.canShowCallout = YES;   // 启用默认气泡(title/subtitle)
    view.draggable = YES;        // 可拖拽
    view.enabled = YES;
    return view;

    // 无图标:使用内置水滴大头针
    // SFMPinAnnotationView *pin = [[SFMPinAnnotationView alloc]
    //     initWithAnnotation:annotation reuseIdentifier:@"pin"];
    // pin.pinColor = [UIColor redColor];
    // pin.animatesDrop = YES;
    // return pin;
}

// ── 拖拽监听 ──
- (void)mapView:(SFMapView *)mapView
    annotationView:(SFMAnnotationView *)view
    didChangeDragState:(SFMAnnotationViewDragState)state
        fromOldState:(SFMAnnotationViewDragState)oldState {
    // state: Starting / Dragging / Ending / Canceling
}

// ── 动态更新属性 ──
SFMAnnotationView *view = [self.mapView viewForAnnotation:annotation];
view.image = newIcon;                      // 切换图标
view.transform = CGAffineTransformMakeRotation(45 * M_PI / 180.0);  // 旋转
view.zIndex = 100;                          // 层级
view.hidden = !visible;                     // 可见性
view.draggable = YES;                       // 可拖拽
view.canShowCallout = NO;                  // 禁用 InfoWindow
annotation.coordinate = newPos;            // 移动位置

// ── 销毁 ──
[self.mapView removeAnnotation:annotation];          // 移除单个
[self.mapView removeAnnotations:allAnnotations];     // 批量移除

要点 ​

  • iOS 采用注解+视图分离模式:注解(SFMPointAnnotation)携带数据,视图(SFMAnnotationView)负责展示,通过 dequeueReusableAnnotationViewWithIdentifier: 复用。
  • SFMPinAnnotationView 是内置水滴大头针,设置 pinColor 和 animatesDrop 即可;如需自定义图标,使用 SFMAnnotationView 并设置 image 属性。
  • canShowCallout = YES 启用默认气泡,点击 Marker 后自动弹出 title/subtitle;可通过 leftCalloutAccessoryView / rightCalloutAccessoryView 添加左右辅助视图。
  • viewForAnnotation: 返回前必须设置好所有属性(如 draggable、canShowCallout),因为该属性在布局阶段仅读取一次。
  • 锚点(centerOffset)通过 [SFMAnnotationView centerOffsetForAnchor:imageSize:] 计算,参数为归一化值(0~1),(0.5, 1.0) 表示底部中心。修改锚点后需移除并重新添加注解以强制重绘(注意同帧 remove+add 同一 symbol 可能触发崩溃,需延迟到下一帧)。

自定义 Marker 视图 ​

功能说明 ​

当内置大头针或纯图片 Marker 无法满足需求时,可继承 SFMAnnotationView 完全自绘视图。Demo 中 SFMDemoPinAnnotationView 用 CAShapeLayer 绘制水滴形图钉,头部叠加 UILabel 显示文字标签,并支持选中态变色。

关键代码 ​

objc
// ── 自定义注解视图子类 ──
@interface SFMDemoPinAnnotationView : SFMAnnotationView
@property (nonatomic, strong) UIColor *pinColor;           // 默认填充色
@property (nonatomic, strong) UIColor *selectedPinColor;    // 选中态填充色
- (void)refreshLabel;  // 同步 annotation.title 到标签
@end

@implementation SFMDemoPinAnnotationView

- (instancetype)initWithAnnotation:(id<SFMAnnotation>)annotation
                     reuseIdentifier:(NSString *)reuseId {
    self = [super initWithAnnotation:annotation reuseIdentifier:reuseId];
    if (self) {
        _pinColor = [UIColor colorWithRed:0xD9/255.0 green:0x22/255.0 blue:0x31/255.0 alpha:1.0];
        _selectedPinColor = [UIColor colorWithRed:0x22/255.0 green:0x66/255.0 blue:0xEE/255.0 alpha:1.0];
        self.bounds = CGRectMake(0, 0, 24, 32);
        [self setupLayers];  // 创建 CAShapeLayer + UILabel
    }
    return self;
}

// 用 CAShapeLayer 绘制水滴路径
+ (UIBezierPath *)pinPathInBounds:(CGRect)bounds {
    CGFloat w = bounds.size.width, h = bounds.size.height;
    CGFloat r = w / 2.0;
    CGFloat cx = w / 2.0, cy = r;
    // ... 切线水滴路径构建
}

// 选中态变色
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    self.pinLayer.fillColor = (selected ? self.selectedPinColor : self.pinColor).CGColor;
}

// 复用时复位
- (void)prepareForReuse {
    [super prepareForReuse];
    self.pinLayer.fillColor = self.pinColor.CGColor;
}
@end

// ── 在 delegate 中使用自定义视图 ──
- (SFMAnnotationView *)mapView:(SFMapView *)mapView
               viewForAnnotation:(id<SFMAnnotation>)annotation {
    static NSString *reuseId = @"customPin";
    SFMDemoPinAnnotationView *view = (SFMDemoPinAnnotationView *)
        [mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
    if (!view) {
        view = [[SFMDemoPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
    }
    view.annotation = annotation;
    view.draggable = YES;
    view.canShowCallout = YES;
    [view refreshLabel];  // 复用时同步标签
    return view;
}

// ── 选中回调 ──
- (void)mapView:(SFMapView *)mapView didSelectAnnotationView:(SFMAnnotationView *)view {
    // view 已切换为选中态颜色
}

要点 ​

  • 继承 SFMAnnotationView 后可在 initWithAnnotation:reuseIdentifier: 中添加自定义 sublayer/subview。
  • prepareForReuse 必须复位状态,因为视图会被复用于不同注解。
  • setSelected:animated: 可覆写以实现选中态视觉变化。
  • refreshLabel 在 viewForAnnotation: 中每次调用,确保复用时标签文字与当前 annotation 同步。

Polyline 多段线 ​

功能说明 ​

在地图上绘制折线,支持实线、虚线、纹理贴图、多线段(单条 Polyline 承载多条独立折线)、半透明等。Polyline 采用模型(SFMPolyline)+ 视图(SFMPolylineView)分离模式。

关键代码 ​

objc
// ── 基本折线 ──
CLLocationCoordinate2D coords[3] = {
    CLLocationCoordinate2DMake(22.53, 113.93),
    CLLocationCoordinate2DMake(22.55, 113.94),
    CLLocationCoordinate2DMake(22.53, 113.95),
};
SFMPolyline *polyline = [SFMPolyline polylineWithCoordinates:coords count:3];
[self.mapView addOverlay:polyline];

// ── 多线段(单条 Polyline 承载多条独立折线)──
NSArray<NSValue *> *line1 = @[/* CLLocationCoordinate2D 包装为 NSValue */];
NSArray<NSValue *> *line2 = @[/* ... */];
SFMPolyline *multi = [SFMPolyline polylineWithMultiLine:@[line1, line2]];
[self.mapView addOverlay:multi];

// ── delegate: 设置折线样式 ──
- (SFMOverlayView *)mapView:(SFMapView *)mapView viewForOverlay:(id<SFMOverlay>)overlay {
    if ([overlay isKindOfClass:[SFMPolyline class]]) {
        SFMPolylineView *view = [[SFMPolylineView alloc] initWithPolyline:(SFMPolyline *)overlay];
        view.strokeEnabled = YES;
        view.strokeColor = [UIColor redColor];
        view.lineWidth = 10.0;
        // 虚线
        view.lineDashPattern = @[@0.5, @2];  // dash/gap,单位为线宽倍数
        // 纹理
        view.textureImage = arrowTextureImage;
        // 半透明
        view.alpha = 0.5;
        return view;
    }
    return nil;
}

// ── 动态更新属性 ──
polylineView.strokeColor = [UIColor blueColor];
polylineView.lineWidth = 12.0;
polylineView.lineDashPattern = nil;           // 关闭虚线
polylineView.alpha = 0.5;                     // 透明度 0~1
polylineView.textureImage = nil;              // 关闭纹理
polylineView.hidden = !visible;               // 可见性
polylineView.zIndex = 100;

// ── 更新折线坐标 ──
CLLocationCoordinate2D *buf = malloc(sizeof(CLLocationCoordinate2D) * (n + 1));
[polyline getCoordinates:buf range:NSMakeRange(0, n)];
buf[n] = newCoord;  // 追加点
[polyline setCoordinates:buf count:n + 1];
free(buf);

// ── 移除 ──
[self.mapView removeOverlay:polyline];
[self.mapView removeOverlays:allPolylines];

要点 ​

  • lineDashPattern 数值单位为 lineWidth 的倍数(屏幕长度 = 值 × lineWidth),@[@0.5, @2] 表示短虚线。
  • textureImage 纹理图建议宽度为 2 的幂(如 32×8),沿线平铺形成流向指示。
  • alpha 范围 0(全透明)~ 1(不透明),通过 view 的 alpha 属性控制。
  • setMultiLine: 可在单个 Polyline 对象中承载多条独立折线,参数为 NSArray<NSArray<NSValue *> *>。
  • 修改模型坐标后(setCoordinates:count:),视图会自动更新;但 MultiPolyline 修改几何后需手动调用 invalidatePath 触发重建。

MultiPolyline 分段颜色折线 ​

功能说明 ​

SFMMultiPolyline 支持在单条折线上按断点分段着色,每段可使用不同颜色,段间可开启渐变过渡。还可使用分段纹理(SFMMultiTexturePolylineView),每段贴不同纹理图。

关键代码 ​

objc
// ── 分段颜色折线 ──
CLLocationCoordinate2D coords[8] = { /* 8 个点 */ };
// drawStyleIndexes 指定断点位置:[2, 5] → 0-2 / 2-5 / 5-末 三段
NSArray<NSNumber *> *indexes = @[@2, @5];
SFMMultiPolyline *pl = [SFMMultiPolyline polylineWithCoordinates:coords
                                                            count:8
                                                 drawStyleIndexes:indexes];
[self.mapView addOverlay:pl];

// ── delegate: 颜色折线视图 ──
- (SFMOverlayView *)mapView:(SFMapView *)mapView viewForOverlay:(id<SFMOverlay>)overlay {
    if ([overlay isKindOfClass:[SFMMultiPolyline class]]) {
        SFMMultiColoredPolylineView *view = [[SFMMultiColoredPolylineView alloc] initWithMultiPolyline:pl];
        view.strokeEnabled = YES;
        view.strokeColors = @[color1, color2, color3];  // 每段一个颜色
        view.gradient = YES;      // 段间渐变过渡
        view.lineWidth = 8.0;
        return view;
    }
    return nil;
}

// ── 分段纹理折线 ──
SFMMultiTexturePolylineView *view = [[SFMMultiTexturePolylineView alloc] initWithPolyline:pl];
view.strokeEnabled = YES;
view.lineWidth = 12.0;
[view loadStrokeTextureImages:@[texture1, texture2, texture3]];  // 每段一个纹理

// ── 动态更新 ──
view.strokeColors = newColorSet;  // 切换段色组
view.gradient = NO;               // 关闭渐变
view.lineWidth = 12.0;
view.hidden = !visible;

要点 ​

  • drawStyleIndexes 定义段断点位置,段数 = indexes.count + 1。颜色数组元素数必须等于段数。
  • gradient = YES 时段间颜色平滑过渡;gradient = NO 时段间硬切。
  • 分段纹理使用 SFMMultiTexturePolylineView,通过 loadStrokeTextureImages: 加载纹理图数组,纹理图数也必须等于段数。
  • 纹理必须在 addOverlay: 之前挂上,否则 viewForOverlay: 拿不到纹理会退回匀色视图。
  • 修改 MultiPolyline 几何后需手动调用 invalidatePath 触发 renderer 重建几何。

Polygon 多边形 ​

功能说明 ​

绘制填充多边形,支持带洞(内环)、自定义填充色/描边色/线宽、填充纹理和描边纹理。同样采用模型(SFMPolygon)+ 视图(SFMPolygonView)分离模式。

关键代码 ​

objc
// ── 基本多边形 ──
CLLocationCoordinate2D coords[4] = {
    CLLocationCoordinate2DMake(lat - 0.005, lng - 0.005),
    CLLocationCoordinate2DMake(lat - 0.005, lng + 0.005),
    CLLocationCoordinate2DMake(lat + 0.005, lng + 0.005),
    CLLocationCoordinate2DMake(lat + 0.005, lng - 0.005),
};
SFMPolygon *polygon = [SFMPolygon polygonWithCoordinates:coords count:4];
[self.mapView addOverlay:polygon];

// ── 带洞多边形 ──
CLLocationCoordinate2D outer[4] = { /* 外环顶点 */ };
CLLocationCoordinate2D holeCoords[4] = { /* 内洞顶点 */ };
SFMPolygon *hole = [SFMPolygon polygonWithCoordinates:holeCoords count:4];
SFMPolygon *polygon = [SFMPolygon polygonWithCoordinates:outer
                                                    count:4
                                         interiorPolygons:@[hole]];
[self.mapView addOverlay:polygon];

// ── delegate: 设置多边形样式 ──
- (SFMOverlayView *)mapView:(SFMapView *)mapView viewForOverlay:(id<SFMOverlay>)overlay {
    if ([overlay isKindOfClass:[SFMPolygon class]]) {
        SFMPolygonView *view = [[SFMPolygonView alloc] initWithPolygon:(SFMPolygon *)overlay];
        view.strokeEnabled = YES;
        view.fillEnabled = YES;
        view.fillColor = [UIColor colorWithRed:0 green:1 blue:0 alpha:0.31];
        view.strokeColor = [UIColor greenColor];
        view.lineWidth = 4.0;
        // 填充纹理
        view.fillTextureImage = checkerTexture;
        // 描边纹理
        view.textureImage = arrowTexture;
        return view;
    }
    return nil;
}

// ── 动态更新 ──
polygonView.fillColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:0.31];
polygonView.strokeColor = [UIColor blueColor];
polygonView.lineWidth = 6.0;
polygonView.fillTextureImage = nil;       // 关闭填充纹理
polygonView.textureImage = nil;            // 关闭描边纹理
polygonView.hidden = !visible;
polygonView.zIndex = 100;

// ── 更新顶点 ──
[polygon getCoordinates:buf range:NSMakeRange(0, n)];
// 修改 buf 中的坐标...
[polygon setCoordinates:buf count:n];
[polygonView invalidatePath];  // 手动触发重建几何

// ── 移除 ──
[self.mapView removeOverlay:polygon];

要点 ​

  • fillColor 建议带 alpha(如 alpha:0.31)以便看到底层地图。
  • interiorPolygons: 参数为内洞多边形数组,支持多个洞。
  • 纹理图建议尺寸为 2 的幂(如 16×16),以确保无缝平铺。
  • 修改模型顶点后(setCoordinates:count:),需手动调用 invalidatePath 触发 renderer 重建几何。
  • fillEnabled / strokeEnabled 可独立控制填充和描边的显示。

Circle 圆形 ​

功能说明 ​

以指定中心点和半径(米)绘制圆,支持填充色、描边色、线宽。同样采用模型(SFMCircle)+ 视图(SFMCircleView)分离模式。可动态更新半径和中心点。

关键代码 ​

objc
// ── 添加圆形 ──
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(22.5429, 113.9414);
SFMCircle *circle = [SFMCircle circleWithCenterCoordinate:center radius:1000];  // 半径 1000 米
[self.mapView addOverlay:circle];

// ── delegate: 设置圆形样式 ──
- (SFMOverlayView *)mapView:(SFMapView *)mapView viewForOverlay:(id<SFMOverlay>)overlay {
    if ([overlay isKindOfClass:[SFMCircle class]]) {
        SFMCircleView *view = [[SFMCircleView alloc] initWithCircle:(SFMCircle *)overlay];
        view.strokeEnabled = YES;
        view.fillEnabled = YES;
        view.numberOfSegments = 64;  // 圆的分段数,越大越圆滑
        view.fillColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.24];
        view.strokeColor = [UIColor redColor];
        view.lineWidth = 4.0;
        return view;
    }
    return nil;
}

// ── 动态更新 ──
circleView.fillColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:0.24];
circleView.strokeColor = [UIColor blueColor];
circleView.lineWidth = 8.0;
circleView.hidden = !visible;
circleView.zIndex = 100;

// 更新半径(米)
circle.radius = 2000;

// 更新中心点
circle.coordinate = newCenter;

// ── 点是否在圆内(手动距离计算)──
CLLocation *c1 = [[CLLocation alloc] initWithLatitude:circle.coordinate.latitude
                                            longitude:circle.coordinate.longitude];
CLLocation *c2 = [[CLLocation alloc] initWithLatitude:testLat longitude:testLng];
BOOL inside = ([c1 distanceFromLocation:c2] <= circle.radius);

// ── 移除 ──
[self.mapView removeOverlay:circle];

要点 ​

  • radius 单位为米,非像素。
  • numberOfSegments 控制圆的分段数,默认 64,越大越圆滑。
  • iOS SDK 未提供 contains: 方法,需用 CLLocation 的 distanceFromLocation: 手动计算球面距离判断。
  • 修改 circle.radius 和 circle.coordinate 后视图会自动更新。

Arc 弧线 ​

功能说明 ​

通过起点、中间控制点、终点三点确定一条弧线。SFMArc 继承自 SFMMultiPoint,渲染走与 Polyline 相同的线型路径(SFMArcView),支持颜色和线宽。

关键代码 ​

objc
// ── 添加弧线 ──
CLLocationCoordinate2D start = CLLocationCoordinate2DMake(22.5429, 113.9414);
CLLocationCoordinate2D mid   = CLLocationCoordinate2DMake(22.5529, 113.9514);
CLLocationCoordinate2D end   = CLLocationCoordinate2DMake(22.5429, 113.9614);
SFMArc *arc = [SFMArc arcWithStartCoordinate:start
                           passedCoordinate:mid
                              endCoordinate:end];
[self.mapView addOverlay:arc];

// ── delegate: 设置弧线样式 ──
- (SFMOverlayView *)mapView:(SFMapView *)mapView viewForOverlay:(id<SFMOverlay>)overlay {
    if ([overlay isKindOfClass:[SFMArc class]]) {
        SFMArcView *view = [[SFMArcView alloc] initWithArc:(SFMArc *)overlay];
        view.strokeEnabled = YES;
        view.fillEnabled = NO;       // 弧线无填充
        view.strokeColor = [UIColor redColor];
        view.lineWidth = 8.0;
        return view;
    }
    return nil;
}

// ── 动态更新 ──
arcView.strokeColor = [UIColor blueColor];
arcView.lineWidth = 12.0;
arcView.hidden = !visible;
arcView.zIndex = 100;

// 追加/重置点
CLLocationCoordinate2D *buf = malloc(sizeof(CLLocationCoordinate2D) * (n + 1));
[arc getCoordinates:buf range:NSMakeRange(0, n)];
buf[n] = newCoord;
[arc setCoordinates:buf count:n + 1];
free(buf);

// ── 移除 ──
[self.mapView removeOverlay:arc];

要点 ​

  • arcWithStartCoordinate:passedCoordinate:endCoordinate: 三点确定弧线,中间点为弧线经过的控制点。
  • Arc 仅支持描边属性(strokeColor / strokeWidth),无填充。
  • pointCount 可查询弧线当前点数;getCoordinates:range: 和 setCoordinates:count: 用于读写坐标。

V3.2-202604301400