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

iOS 15下如何移除MapKit地图默认标注(商铺、餐厅等)

iOS 15 下移除 MapKit 默认商铺/餐厅等标注的实现方案

在 iOS 15 中,SwiftUI 原生的 Map 组件没有直接提供隐藏 POI(商铺、餐厅这类第三方标注)的参数,需要通过包装 UIKit 的 MKMapView 来实现自定义控制。下面是适配后的完整代码:

import SwiftUI
import MapKit
import CoreLocation

// 包装 UIKit 的 MKMapView,实现标注过滤逻辑
struct CustomMapView: UIViewRepresentable {
    @Binding var region: MKCoordinateRegion
    var showsUserLocation: Bool
    var userTrackingMode: MKUserTrackingMode
    
    func makeUIView(context: Context) -> MKMapView {
        let mapView = MKMapView()
        mapView.delegate = context.coordinator
        mapView.showsUserLocation = showsUserLocation
        mapView.userTrackingMode = userTrackingMode
        return mapView
    }
    
    func updateUIView(_ uiView: MKMapView, context: Context) {
        uiView.setRegion(region, animated: true)
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, MKMapViewDelegate {
        var parent: CustomMapView
        
        init(_ parent: CustomMapView) {
            self.parent = parent
        }
        
        // 过滤系统标注:仅保留用户位置标注,其余全部隐藏
        func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
            if annotation is MKUserLocation {
                return mapView.dequeueReusableAnnotationView(withIdentifier: MKMapViewDefaultUserLocationAnnotationViewIdentifier)
            }
            // 返回 nil 表示不渲染该标注,以此隐藏所有 POI
            return nil
        }
    }
}

// 替换原 SwiftUI 视图,使用自定义地图组件
struct MapView: View {
    let locationManager = CLLocationManager()
    
    @State var region = MKCoordinateRegion(
        center: .init(latitude: 37.334_900, longitude: -122.009_020),
        span: .init(latitudeDelta: 0.2, longitudeDelta: 0.2)
    )
    
    var body: some View {
        ZStack {
            CustomMapView(
                region: $region,
                showsUserLocation: true,
                userTrackingMode: .follow
            )
            .edgesIgnoringSafeArea(.all)
            .onAppear {
                locationManager.requestWhenInUseAuthorization()
            }
        }
    }
}

关键逻辑说明

  1. UIKit 桥接:通过 UIViewRepresentable 将 MKMapView 接入 SwiftUI 环境,这是 iOS 15 下实现自定义地图行为的标准方式。
  2. 标注过滤:在 MKMapViewDelegate 的 mapView(_:viewFor:) 方法中,仅对用户位置标注做正常渲染,其余所有系统标注(包括各类 POI)返回 nil,从而实现隐藏效果。
  3. 功能保留:完全保留了你原代码中的用户位置授权、区域显示、位置跟踪等功能,仅新增标注过滤逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 20:22:32