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

如何在Map View中添加多个Pin(MapMarker)?添加报错求解决

解决Map View标记位置不生效的问题

你的代码核心问题是没有使用预先定义好的locations数组作为标注数据源,而是在annotationItems里手动创建了单个PinItem,导致只有一个标记被加载,其他位置的标记无法显示。

修改步骤:

  1. 将Map初始化时的annotationItems参数值替换为你已经定义好的locations数组
  2. (可选)如果需要用户与地图交互(比如缩放、拖动),调整interactionModes参数,比如设置为.all或具体的交互模式(如.zoom、.pan)

修改后的完整代码:

struct Store_locator_page: View {

    struct PinItem: Identifiable{
        let id = UUID()
        let coordinate: CLLocationCoordinate2D
    }

    @State var region = MKCoordinateRegion(center:.init(latitude: -32.5, longitude: 115.75),latitudinalMeters: 1000, longitudinalMeters: 1000)

    let locations = [
        PinItem(coordinate: .init(latitude: -32.5, longitude: 115.75)),
        PinItem(coordinate: .init(latitude: -32.7, longitude: 115.9)),
        PinItem(coordinate: .init(latitude: -32.6, longitude: 115.8)),
        PinItem(coordinate: .init(latitude: -32.4, longitude: 115.7))
    ]

    var body: some View {
        ScrollView{
            Map(coordinateRegion : $region,
                interactionModes: .all, // 启用全部交互模式,可根据需求调整
                showsUserLocation: true,
                userTrackingMode: nil,
                annotationItems: locations // 替换为预定义的locations数组
            ) { item in
                MapMarker(coordinate: item.coordinate)
            }
        }
    }
}

额外说明:

  • PinItem已经实现了Identifiable协议,符合Map对标注数据源的要求,无需额外修改
  • 如果需要自定义标记样式,可以将MapMarker替换为MapAnnotation,添加自定义的View作为标记

内容的提问来源于stack exchange,提问作者Gimhan Ariyarathna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:05:36