Mapbox Ios Patterns

作者 mapboxaab3a6fef5c6无许可证收录于 2026年10月8日更新于 2026年10月8日

Official integration patterns for Mapbox Maps SDK on iOS. Covers installation, adding markers, user location, custom data, styles, camera control, and featureset interactions. Based on official Mapbox documentation.

AI 生成的概览

提供 iOS 上 Mapbox Maps SDK v11 的官方集成模式,涵盖 Swift、SwiftUI 与 UIKit。

功能
该技能提供将 Mapbox Maps SDK v11 集成到 iOS 项目中的参考指南与代码模式。内容涵盖安装与访问令牌配置、SwiftUI 与 UIKit 的地图初始化、添加标记与注记、显示用户位置、自定义 GeoJSON 数据、地图样式、相机控制、要素交互、性能实践与故障排查。它产出代码片段和配置步骤,而非可直接运行的脚本。
适用场景
适用于开发或维护内嵌 Mapbox 地图的 iOS 应用,并需要关于初始化、注记、位置显示、自定义数据、样式或手势的具体模式时。也适合排查地图不显示、样式加载失败或注记性能问题。
运行要求
需要一个 iOS 14+ 项目,使用 Xcode 15+ 与 Swift 5.9+,通过 Swift Package Manager、CocoaPods 或直接下载方式加入 Mapbox Maps SDK v11,并拥有一个免费 Mapbox 账户及写入 Info.plist 的公开访问令牌。位置功能需要 CoreLocation 权限声明。该技能不包含脚本,仅为说明与参考文档。

Mapbox iOS Integration Patterns

Official patterns for integrating Mapbox Maps SDK v11 on iOS with Swift, SwiftUI, and UIKit.

Use this skill when:

  • Installing and configuring Mapbox Maps SDK for iOS
  • Adding markers and annotations to maps
  • Showing user location and tracking with camera
  • Adding custom data (GeoJSON) to maps
  • Working with map styles, camera, or user interaction
  • Handling feature interactions and taps

Official Resources:


Installation & Setup

Requirements

  • iOS 14+
  • Xcode 15+
  • Swift 5.9+
  • Free Mapbox account

Step 1: Configure Access Token

Add your public token to Info.plist:

xml
<key>MBXAccessToken</key><string>pk.your_mapbox_token_here</string>

Get your token: Sign in at mapbox.com

Step 2: Add Swift Package Dependency

  1. File → Add Package Dependencies
  2. Enter URL: https://github.com/mapbox/mapbox-maps-ios.git
  3. Version: "Up to Next Major" from 11.0.0
  4. Verify four dependencies appear: MapboxCommon, MapboxCoreMaps, MapboxMaps, Turf

Alternative: CocoaPods or direct download (install guide)


Map Initialization

SwiftUI Pattern

Basic map:

swift
import SwiftUIimport MapboxMaps
struct ContentView: View {    @State private var viewport: Viewport = .camera(        center: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194),        zoom: 12    )
    var body: some View {        Map(viewport: $viewport)            .mapStyle(.standard)    }}

With ornaments:

swift
Map(viewport: $viewport)    .mapStyle(.standard)    .ornamentOptions(OrnamentOptions(        scaleBar: .init(visibility: .visible),        compass: .init(visibility: .adaptive),        logo: .init(position: .bottomLeading)    ))

UIKit Pattern

swift
import UIKitimport MapboxMaps
class MapViewController: UIViewController {    private var mapView: MapView!
    override func viewDidLoad() {        super.viewDidLoad()
        let options = MapInitOptions(            cameraOptions: CameraOptions(                center: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194),                zoom: 12            )        )
        mapView = MapView(frame: view.bounds, mapInitOptions: options)        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]        view.addSubview(mapView)
        mapView.mapboxMap.loadStyle(.standard)    }}

Add Markers

The SDK offers three ways to place a point on the map. Pick the simplest one that fits.

Agent note: A SwiftUI Mapbox sketch is incomplete without at least one annotation (Marker, PointAnnotation, or MapViewAnnotation). Do not ship a bare Map { } with no pin.

Which API should I use?

APIUse it whenPlatformsNotes
Marker (Markers API)You need a default pin and don't have a custom image assetSwiftUI onlyNo image assets required. Experimental SPI — needs @_spi(Experimental) import MapboxMaps. Best < 100 markers.
PointAnnotationYou have a custom image and want layer-level placementSwiftUI + UIKitBacked by a symbol layer, so it scales well to hundreds of markers. Accepts any UIImage that UIKit can render.
View annotations (ViewAnnotation / MapViewAnnotation)You want to render a full native view (card, badge, animated content) anchored to a coordinateSwiftUI + UIKitSwiftUI uses MapViewAnnotation; UIKit uses mapView.viewAnnotations with a ViewAnnotation. Each annotation is a real view — costs more than PointAnnotation at scale.

For hundreds or thousands of features, use a style layer (SymbolLayer on a GeoJSONSource) instead of annotations.

Markers API (recommended for simple cases, SwiftUI)

swift
import SwiftUI@_spi(Experimental) import MapboxMaps
struct ContentView: View {    var body: some View {        Map {            Marker(coordinate: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194))                .color(.red)                .text("San Francisco")        }    }}

Multiple markers from a collection:

swift
Map {    ForEvery(locations, id: \.id) { location in        Marker(coordinate: location.coordinate)            .color(.red)            .text(location.name)    }}

Scaling note. Marker and PointAnnotation each create their own view or symbol entry per pin — fine up to about 100 markers. For larger datasets (hundreds or thousands of features — common with open-ended GeoJSON feeds), load the data into a GeoJSONSource and render it with a SymbolLayer instead. That scales to thousands of features and enables clustering.

PointAnnotation (custom image)

SwiftUI:

swift
Map(viewport: $viewport) {    PointAnnotation(coordinate: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194))        .image(.init(image: UIImage(named: "marker")!, name: "marker"))}

UIKit:

swift
// Create annotation manager (once, reuse for updates)var pointAnnotationManager = mapView.annotations.makePointAnnotationManager()
// Create markervar annotation = PointAnnotation(coordinate: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194))annotation.image = .init(image: UIImage(named: "marker")!, name: "marker")annotation.iconAnchor = .bottom
// Add to mappointAnnotationManager.annotations = [annotation]

Multiple markers:

swift
let annotations = locations.map { coordinate in    var annotation = PointAnnotation(coordinate: coordinate)    annotation.image = .init(image: UIImage(named: "marker")!, name: "marker")    return annotation}
pointAnnotationManager.annotations = annotations

Show User Location

Step 1: Add location permission to Info.plist:

xml
<key>NSLocationWhenInUseUsageDescription</key><string>Show your location on the map</string>

Step 2: Request permissions and show location:

swift
import CoreLocation
// Request permissionslet locationManager = CLLocationManager()locationManager.requestWhenInUseAuthorization()
// Show user location puckmapView.location.options.puckType = .puck2D()mapView.location.options.puckBearingEnabled = true

Performance Best Practices

Reuse Annotation Managers

swift
// ❌ Don't create new managers repeatedlyfunc updateMarkers() {    let manager = mapView.annotations.makePointAnnotationManager()    manager.annotations = markers}
// ✅ Create once, reuselet pointAnnotationManager: PointAnnotationManager
init() {    pointAnnotationManager = mapView.annotations.makePointAnnotationManager()}
func updateMarkers() {    pointAnnotationManager.annotations = markers}

Batch Annotation Updates

swift
// ✅ Update all at oncepointAnnotationManager.annotations = newAnnotations
// ❌ Don't update one by onefor annotation in newAnnotations {    pointAnnotationManager.annotations.append(annotation)}

Memory Management

swift
// Use weak self in closuresmapView.gestures.onMapTap.observe { [weak self] context in    self?.handleTap(context.coordinate)}.store(in: &cancelables)
// Clean up on deinitdeinit {    cancelables.forEach { $0.cancel() }}

Use Standard Style

swift
// ✅ Standard style is optimized and recommended.mapStyle(.standard)
// Use other styles only when needed for specific use cases.mapStyle(.standardSatellite) // Satellite imagery

Troubleshooting

Map Not Displaying

Check:

  1. ✅ MBXAccessToken in Info.plist
  2. ✅ Token is valid (test at mapbox.com)
  3. ✅ MapboxMaps framework imported
  4. ✅ MapView added to view hierarchy
  5. ✅ Correct frame/constraints set

Style Not Loading

swift
mapView.mapboxMap.onStyleLoaded.observe { [weak self] _ in    print("Style loaded successfully")    // Add layers and sources here}.store(in: &cancelables)

Performance Issues

  • Use .standard style (recommended and optimized)
  • Limit visible annotations to viewport
  • Reuse annotation managers
  • Avoid frequent style reloads
  • Batch annotation updates

Reference Files

Load these references when the task requires deeper patterns:

  • references/annotations.md — Circle, Polyline, Polygon Annotations
  • references/location-tracking.md — Camera Follow User + Get Current Location
  • references/custom-data.md — GeoJSON: Lines, Polygons, Points, Update/Remove
  • references/camera-styles.md — Camera Control + Map Styles
  • references/interactions.md — Featureset Interactions, Custom Layer Taps, Long Press, Gestures

Additional Resources

来源与署名

来源:mapbox/mapbox-agent-skills位于skills/mapbox-ios-patterns提交aab3a6f

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架