You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MapBox Maps iOS SDK v10.1.0 选中PointAnnotation时如何添加动画效果?

Mapbox Maps iOS v10 点标注点击缩放动画实现方案

核心逻辑

Mapbox v10 中PointAnnotation为值类型,不再关联UIView实例,所有渲染属性修改都需要通过标注管理器(AnnotationManager)配合SDK自带的动画API实现,不需要手动操作底层图层。

实现步骤

  • 步骤1:初始化点标注管理器并开启交互
    首先创建PointAnnotationManager,并设置交互代理接收点击事件:
    import MapboxMaps
    
    // 初始化标注管理器
    let pointAnnotationManager = mapView.annotations.makePointAnnotationManager()
    // 设置交互代理,监听标注点击
    pointAnnotationManager.interactionDelegate = self
    
  • 步骤2:创建标注并配置基础属性
    初始化PointAnnotation时必须设置唯一ID,方便后续点击时定位目标标注:
    var annotation = PointAnnotation(coordinate: targetCoordinate)
    // 配置标注图标,需提前将对应图片注册到Mapbox样式中
    annotation.iconImage = "custom_annotation_icon"
    // 默认缩放比例
    annotation.iconScale = 1.0
    // 设置唯一ID,必填
    annotation.id = UUID().uuidString
    // 添加到标注管理器
    pointAnnotationManager.annotations.append(annotation)
    
  • 步骤3:实现点击回调,触发缩放动画
    实现AnnotationInteractionDelegate代理方法,在点击标注时通过两段动画实现先放大后缩小的效果,总时长350ms:
    extension YourViewController: AnnotationInteractionDelegate {
        func annotationManager(_ manager: AnnotationManager, didDetectTappedAnnotations annotations: [Annotation]) {
            // 过滤出点击的点标注
            guard let tappedAnnotation = annotations.first as? PointAnnotation,
                  let annotationIndex = pointAnnotationManager.annotations.firstIndex(where: { $0.id == tappedAnnotation.id }) else {
                return
            }
            
            // 第一段动画:175ms放大到1.1倍
            mapView.mapboxMap.style.animate(withDuration: 0.175, animations: {
                var scaledAnnotation = tappedAnnotation
                scaledAnnotation.iconScale = 1.1
                self.pointAnnotationManager.annotations[annotationIndex] = scaledAnnotation
            }, completion: { _ in
                // 第二段动画:175ms缩回1.0倍
                self.mapView.mapboxMap.style.animate(withDuration: 0.175, animations: {
                    var resetAnnotation = tappedAnnotation
                    resetAnnotation.iconScale = 1.0
                    self.pointAnnotationManager.annotations[annotationIndex] = resetAnnotation
                })
            })
        }
    }
    

注意事项

  • 若使用自定义View作为标注图标,需要先将View渲染为UIImage,通过style.addImage(_:id:)方法注册到Mapbox样式中,再赋值给annotation.iconImage才可生效
  • 标注的ID必须唯一,否则无法准确定位到需要更新的目标标注
  • 不要直接修改pointAnnotationManager.annotations数组中元素的属性,因为PointAnnotation是值类型,直接修改不会触发渲染更新,需要替换数组中对应索引的元素才能生效

内容的提问来源于stack exchange,提问作者Valerii Lider

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:15:04