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

SwiftUI中通过@Binding的selectedBus经纬度添加MapMarker报错如何解决

问题解决方法

报错原因

  • MapMarker不是独立的SwiftUI视图,不能直接和Map平级放在body的视图序列中,它只能作为Map视图的标注内容,放在annotationContent参数的闭包内使用
  • 你原来的写法同时返回了Map和MapMarker两个元素,MapMarker本身不遵守View协议,所以会触发类型合规性报错

修复步骤

  1. 给Location结构体补充遵守Identifiable协议,满足Map标注数据源的可识别要求
  2. 改用带标注参数的Map构造方法,把MapMarker放到标注内容闭包中

修复后完整代码

import SwiftUI
import MapKit
import CoreLocation

struct BusView: View {
    @Binding var selectedBus : Bus
    @State private var coordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40, longitude: 28), span: MKCoordinateSpan(latitudeDelta: 50, longitudeDelta: 50))

    var body: some View {
        // 改用带标注的Map构造方法,传入筛选后的非空位置作为数据源
        Map(coordinateRegion: $coordinateRegion, annotationItems: [selectedBus.location].compactMap{$0}) { location in
            MapMarker(coordinate: CLLocationCoordinate2D(latitude: location.latitude ?? 0, longitude: location.longitude ?? 0), tint: .red)
        }
    }
}

struct Bus: Decodable, Hashable {
    let remainingTime: Int?
    let plate: String?
    let routeCode: String?
    let icon: String?
    let location: Location?
}

struct Location: Decodable, Hashable, Identifiable {
    // 新增Identifiable要求的id属性
    let id = UUID()
    let latitude: Double?
    let longitude: Double?
}

如果项目需要兼容更低系统版本,也可以替换为MapAnnotation实现,逻辑完全一致。

内容的提问来源于stack exchange,提问作者Mert Köksal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:48:00