Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

mapkit-location地图包位置

Agent Skill

mapkit-location 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

11,088

周安装

462

GitHub Stars

523

下载量

3,696
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:mapkit-location(地图包位置)
来源仓库:https://github.com/dpearson2699/swift-ios-skills
仓库路径:skills/mapkit-location
安装命令:
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill mapkit-location
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill mapkit-location

简介

使用 SwiftUI MapKit 和现代 CoreLocation 异步 API 为 iOS 17+ 构建地图和位置功能。

  • 支持SwiftUI地图
  • 带有标记、注释、折线、多边形和圆的视图;包括相机定位、风格选项和交互模式
  • 提供 CLLocationUpdate.liveUpdates()
  • 用于位置跟踪和 CLMonitor 的异步流
  • 用于具有多达 20 个监控条件的地理围栏
  • 涵盖地理编码(正向和反向)、通过 MKLocalSearchCompleter 自动完成的本地搜索,以及跨多种运输类型的 ETA 计算的方向
  • 包括 CLServiceSession
  • 用于显式授权管理 (iOS 18+) 和 PlaceDescriptor
  • 用于丰富地点查找(iOS 26+)
  • 常见错误部分和检查清单有助于避免电池耗尽、权限问题和地理编码失败

SKILL.md

MapKit and CoreLocation

Build map-based and location-aware features targeting iOS 17+ with SwiftUI MapKit and modern CoreLocation async APIs. Use Map with MapContentBuilder for views, CLLocationUpdate.liveUpdates() for streaming location, and CLMonitor for geofencing.

See references/mapkit-patterns.md for extended MapKit patterns and references/corelocation-patterns.md for CoreLocation patterns.

Contents

Workflow

1. Add a map with markers or annotations

  1. Import MapKit.
  2. Create a Map view with optional MapCameraPosition binding.
  3. Add Marker, Annotation, MapPolyline, MapPolygon, or MapCircle inside the MapContentBuilder closure.
  4. Configure map style with .mapStyle().
  5. Add map controls with .mapControls {}.
  6. Handle selection with a selection: binding.

2. Track user location

  1. Add NSLocationWhenInUseUsageDescription to Info.plist.
  2. On iOS 18+, create a CLServiceSession to manage authorization.
  3. Iterate CLLocationUpdate.liveUpdates() in a Task.
  4. Filter updates by distance or accuracy before updating the UI.
  5. Stop the task when location tracking is no longer needed.

3. Search for places

  1. Configure MKLocalSearchCompleter for autocomplete suggestions.
  2. Debounce user input (at least 300ms) before setting the query.
  3. Convert selected completion to MKLocalSearch.Request for full results.
  4. Display results as markers or in a list.

4. Get directions and display a route

  1. Create an MKDirections.Request with source and destination MKMapItem.
  2. Set transportType (.automobile, .walking, .transit, .cycling).
  3. Await MKDirections.calculate().
  4. Draw the route with MapPolyline(route.polyline).

5. Review existing map/location code

Run through the Review Checklist at the end of this file.

SwiftUI Map View (iOS 17+)

import MapKit
import SwiftUI

struct PlaceMap: View {
    @State private var position: MapCameraPosition = .automatic

    var body: some View {
        Map(position: $position) {
            Marker("Apple Park", coordinate: applePark)
            Marker("Infinite Loop", systemImage: "building.2",
                   coordinate: infiniteLoop)
        }
        .mapStyle(.standard(elevation: .realistic))
        .mapControls {
            MapUserLocationButton()
            MapCompass()
            MapScaleView()
        }
    }
}

Marker and Annotation

// Balloon marker -- simplest way to pin a location
Marker("Cafe", systemImage: "cup.and.saucer.fill", coordinate: cafeCoord)
    .tint(.brown)

// Annotation -- custom SwiftUI view at a coordinate
Annotation("You", coordinate: userCoord, anchor: .bottom) {
    Image(systemName: "figure.wave")
        .padding(6)
        .background(.blue.gradient, in: .circle)
        .foregroundStyle(.white)
}

Overlays: Polyline, Polygon, Circle

Map {
    // Polyline from coordinates
    MapPolyline(coordinates: routeCoords)
        .stroke(.blue, lineWidth: 4)

    // Polygon (area highlight)
    MapPolygon(coordinates: parkBoundary)
        .foregroundStyle(.green.opacity(0.3))
        .stroke(.green, lineWidth: 2)

    // Circle (radius around a point)
    MapCircle(center: storeCoord, radius: 500)
        .foregroundStyle(.red.opacity(0.15))
        .stroke(.red, lineWidth: 1)
}

Camera Position

MapCameraPosition controls what the map displays. Bind it to let the user interact and to programmatically move the camera.

// Center on a region
@State private var position: MapCameraPosition = .region(
    MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 37.334, longitude: -122.009),
        span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
    )
)

// Follow user location
@State private var position: MapCameraPosition = .userLocation(fallback: .automatic)

// Specific camera angle (3D perspective)
@State private var position: MapCameraPosition = .camera(
    MapCamera(centerCoordinate: applePark, distance: 1000, heading: 90, pitch: 60)
)

// Frame specific items
position = .item(MKMapItem.forCurrentLocation())
position = .rect(MKMapRect(...))

Map Style

.mapStyle(.standard)                                        // Default road map
.mapStyle(.standard(elevation: .realistic, showsTraffic: true))
.mapStyle(.imagery)                                         // Satellite
.mapStyle(.imagery(elevation: .realistic))                  // 3D satellite
.mapStyle(.hybrid)                                          // Satellite + labels
.mapStyle(.hybrid(elevation: .realistic, showsTraffic: true))

Map Interaction Modes

.mapInteractionModes(.all)           // Default: pan, zoom, rotate, pitch
.mapInteractionModes(.pan)           // Pan only
.mapInteractionModes([.pan, .zoom])  // Pan and zoom
.mapInteractionModes([])             // Static map (no interaction)

Map Selection

@State private var selectedMarker: MKMapItem?

Map(selection: $selectedMarker) {
    ForEach(places) { place in
        Marker(place.name, coordinate: place.coordinate)
            .tag(place.mapItem)     // Tag must match selection type
    }
}
.onChange(of: selectedMarker) { _, newValue in
    guard let item = newValue else { return }
    // React to selection
}

CoreLocation Modern API

CLLocationUpdate.liveUpdates() (iOS 17+)

Replace CLLocationManagerDelegate callbacks with a single async sequence. Each iteration yields a CLLocationUpdate containing an optional CLLocation.

import CoreLocation

@Observable
final class LocationTracker: @unchecked Sendable {
    var currentLocation: CLLocation?
    private var updateTask: Task<Void, Never>?

    func startTracking() {
        updateTask = Task {
            let updates = CLLocationUpdate.liveUpdates()
            for try await update in updates {
                guard let location = update.location else { continue }
                // Filter by horizontal accuracy
                guard location.horizontalAccuracy < 50 else { continue }
                await MainActor.run {
                    self.currentLocation = location
                }
            }
        }
    }

    func stopTracking() {
        updateTask?.cancel()
        updateTask = nil
    }
}

CLServiceSession (iOS 18+)

Declare authorization requirements for a feature's lifetime. Hold a reference to the session for as long as you need location services.

// When-in-use authorization with full accuracy preference
let session = CLServiceSession(
    authorization: .whenInUse,
    fullAccuracyPurposeKey: "NearbySearchPurpose"
)
// Hold `session` as a stored property; release it when done.

On iOS 18+, CLLocationUpdate.liveUpdates() and CLMonitor take an implicit CLServiceSession if you do not create one explicitly. Create one explicitly when you need .always authorization or full accuracy.

Authorization Flow

// Info.plist keys (required):
// NSLocationWhenInUseUsageDescription
// NSLocationAlwaysAndWhenInUseUsageDescription (only if .always needed)

// Check authorization and guide user to Settings when denied
struct LocationPermissionView: View {
    @Environment(\.openURL) private var openURL

    var body: some View {
        ContentUnavailableView {
            Label("Location Access Denied", systemImage: "location.slash")
        } description: {
            Text("Enable location access in Settings to use this feature.")
        } actions: {
            Button("Open Settings") {
                if let url = URL(string: UIApplication.openSettingsURLString) {
                    openURL(url)
                }
            }
        }
    }
}

Geocoding

CLGeocoder (iOS 8+)

let geocoder = CLGeocoder()

// Forward geocoding: address string -> coordinates
let placemarks = try await geocoder.geocodeAddressString("1 Apple Park Way, Cupertino")
if let location = placemarks.first?.location {
    print(location.coordinate) // CLLocationCoordinate2D
}

// Reverse geocoding: coordinates -> placemark
let location = CLLocation(latitude: 37.3349, longitude: -122.0090)
let placemarks = try await geocoder.reverseGeocodeLocation(location)
if let placemark = placemarks.first {
    let address = [placemark.name, placemark.locality, placemark.administrativeArea]
        .compactMap { $0 }
        .joined(separator: ", ")
}

MKGeocodingRequest and MKReverseGeocodingRequest (iOS 26+)

New MapKit-native geocoding that returns MKMapItem with richer data and MKAddress / MKAddressRepresentations for flexible address formatting.

@available(iOS 26, *)
func reverseGeocode(location: CLLocation) async throws -> MKMapItem? {
    guard let request = MKReverseGeocodingRequest(location: location) else {
        return nil
    }
    let mapItems = try await request.mapItems
    return mapItems.first
}

@available(iOS 26, *)
func forwardGeocode(address: String) async throws -> [MKMapItem] {
    guard let request = MKGeocodingRequest(addressString: address) else { return [] }
    return try await request.mapItems
}

Search

MKLocalSearchCompleter (Autocomplete)

@Observable
final class SearchCompleter: NSObject, MKLocalSearchCompleterDelegate {
    var results: [MKLocalSearchCompletion] = []
    var query: String = "" { didSet { completer.queryFragment = query } }

    private let completer = MKLocalSearchCompleter()

    override init() {
        super.init()
        completer.delegate = self
        completer.resultTypes = [.address, .pointOfInterest]
    }

    func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
        results = completer.results
    }

    func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
        results = []
    }
}

MKLocalSearch (Full Search)

func search(for completion: MKLocalSearchCompletion) async throws -> [MKMapItem] {
    let request = MKLocalSearch.Request(completion: completion)
    request.resultTypes = [.pointOfInterest, .address]
    let search = MKLocalSearch(request: request)
    let response = try await search.start()
    return response.mapItems
}

// Search by natural language query within a region
func searchNearby(query: String, region: MKCoordinateRegion) async throws -> [MKMapItem] {
    let request = MKLocalSearch.Request()
    request.naturalLanguageQuery = query
    request.region = region
    let search = MKLocalSearch(request: request)
    let response = try await search.start()
    return response.mapItems
}

Directions

func getDirections(from source: MKMapItem, to destination: MKMapItem,
                   transport: MKDirectionsTransportType = .automobile) async throws -> MKRoute? {
    let request = MKDirections.Request()
    request.source = source
    request.destination = destination
    request.transportType = transport
    let directions = MKDirections(request: request)
    let response = try await directions.calculate()
    return response.routes.first
}

Display Route on Map

@State private var route: MKRoute?

Map {
    if let route {
        MapPolyline(route.polyline)
            .stroke(.blue, lineWidth: 5)
    }
    Marker("Start", coordinate: startCoord)
    Marker("End", coordinate: endCoord)
}
.task {
    route = try? await getDirections(from: startItem, to: endItem)
}

ETA Calculation

func getETA(from source: MKMapItem, to destination: MKMapItem) async throws -> TimeInterval {
    let request = MKDirections.Request()
    request.source = source
    request.destination = destination
    let directions = MKDirections(request: request)
    let response = try await directions.calculateETA()
    return response.expectedTravelTime
}

Cycling Directions (iOS 26+)

@available(iOS 26, *)
func getCyclingDirections(to destination: MKMapItem) async throws -> MKRoute? {
    let request = MKDirections.Request()
    request.source = MKMapItem.forCurrentLocation()
    request.destination = destination
    request.transportType = .cycling
    let directions = MKDirections(request: request)
    let response = try await directions.calculate()
    return response.routes.first
}

PlaceDescriptor (iOS 26+)

Create rich place references from coordinates or addresses without needing a Place ID. Requires import GeoToolbox.

@available(iOS 26, *)
func lookupPlace(name: String, coordinate: CLLocationCoordinate2D) async throws -> MKMapItem {
    let descriptor = PlaceDescriptor(
        representations: [.coordinate(coordinate)],
        commonName: name
    )
    let request = MKMapItemRequest(placeDescriptor: descriptor)
    return try await request.mapItem
}

Common Mistakes

DON'T: Request .authorizedAlways upfront — users distrust broad permissions. DO: Start with .requestWhenInUseAuthorization(), escalate to .always only when the user enables a background feature.

DON'T: Use CLLocationManagerDelegate for simple location fetches on iOS 17+. DO: Use CLLocationUpdate.liveUpdates() async stream for cleaner, more concise code.

DON'T: Keep location updates running when the map/view is not visible (drains battery). DO: Use .task {} in SwiftUI so updates cancel automatically on disappear.

DON'T: Force-unwrap CLPlacemark properties — they are all optional. DO: Use nil-coalescing: placemark.locality?? "Unknown".

DON'T: Fire MKLocalSearchCompleter queries on every keystroke. DO: Debounce with .task(id: searchText) + Task.sleep(for:.milliseconds(300)).

DON'T: Silently fail when location authorization is denied. DO: Detect .denied status and show an alert with a Settings deep link.

DON'T: Assume geocoding always succeeds — handle empty results and network errors.

Review Checklist

  • Info.plist has NSLocationWhenInUseUsageDescription with specific reason
  • Authorization denial handled with Settings deep link
  • CLLocationUpdate task cancelled when not needed (battery)
  • Location accuracy appropriate for the use case
  • Map annotations use Identifiable data with stable IDs
  • Geocoding errors handled (network failure, no results)
  • Search completer input debounced
  • CLMonitor limited to 20 conditions, instance kept alive
  • Background location uses CLBackgroundActivitySession
  • Map tested with VoiceOver
  • Map annotation view models and location UI updates are @MainActor-isolated

References

  • references/mapkit-patterns.md — Map setup, annotations, search, routes, clustering, Look Around, snapshots.
  • references/corelocation-patterns.md — CLLocationUpdate, CLMonitor, CLServiceSession, background location, testing.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

37.55%
按下载量换算1,388

Claude

29.54%
按下载量换算1,092

Cursor

17.62%
按下载量换算651

Gemini CLI

8.97%
按下载量换算332

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills