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

iOS 18中MapKit的UserAnnotation不显示问题排查与解决

iOS 18 中 UserAnnotation 不显示的问题修复

问题分析

你的代码存在两个核心问题:

  1. 同时渲染两个Map视图:body中保留了已弃用的Map(mapRect:...)占位代码,导致两个地图叠加显示,直接干扰UserAnnotation的正常渲染逻辑。
  2. 缺失位置权限配置与请求:UserAnnotation依赖应用获取用户位置权限,无权限时系统不会加载并显示用户位置标记。

修复步骤

1. 移除弃用的Map代码

直接删除body中未完成的旧版Map初始化代码:

Map(mapRect: <#T##Binding<MKMapRect>#>, showsUserLocation: <#T##Bool#>)

2. 配置位置权限

在项目的Info.plist中添加位置权限描述键(根据需求二选一):

  • 仅前台需要位置:添加NSLocationWhenInUseUsageDescription,值填写权限用途说明(例如:"需要获取您的位置以在地图上显示当前位置")
  • 需要后台位置权限:添加NSLocationAlwaysAndWhenInUseUsageDescription,填写对应的用途说明

3. 请求位置权限

在视图中引入CoreLocation框架,添加位置管理器并在视图出现时请求权限:

4. 可选:添加用户位置跟踪

给Map设置userTrackingMode,让地图自动跟随用户位置,确保UserAnnotation准确显示。

完整修复代码

import SwiftUI
import MapKit
import CoreLocation

struct MapView: View {
    @State var region: MapCameraPosition = .automatic
    @StateObject private var locationManager = CLLocationManager()
    
    var body: some View {
        Map(position: $region, userTrackingMode: .constant(.follow)) {
            Marker(
                "Marker 1",
                systemImage: "heart",
                coordinate: CLLocationCoordinate2D(
                    latitude: 59.447584,
                    longitude: 7.761791
                )
            )
            Marker(
                "Marker 2",
                systemImage: "star",
                coordinate: CLLocationCoordinate2D(
                    latitude: 59.450703,
                    longitude: 7.765370
                )
            )
            .tint(.blue)
            UserAnnotation()
        }
        .onAppear {
            locationManager.requestWhenInUseAuthorization()
        }
    }
}

额外说明

  • 确保用户设备的位置服务已开启,且允许你的应用获取位置权限。
  • 若不需要自动跟随用户位置,可移除userTrackingMode参数,但仍需保证权限已正常获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 08:40:07