MapKit (MapKit)
می خواهیم با «نقشه MapKit» آشنا شویم. MapKit نقشه نشان می دهد. سپس مکان ها و مسیرها را مدیریت می کند. اصطلاح «Annotation» یعنی پین یا نماگر روی نقشه.
نقشه ساده با Region
برای نمایش نقشه، یک «ناحیه دوربین (MapCameraPosition)» می سازیم. سپس به Map وصل می کنیم.
import SwiftUI;
import MapKit;
struct BasicMap: View {
@State private var position: MapCameraPosition = .region(
MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090),
span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
)
);
var body: some View {
Map(position: $position)
.ignoresSafeArea();
}
}
import SwiftUI;
struct ContentView: View {
var body: some View {
BasicMap();
}
}
import SwiftUI;
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView();
}
}
}
این کد نقشه را روی Apple Park می گذارد. بزرگ نمایی هم ملایم است.
Annotation و Marker
«Annotation» یعنی علامت روی مختصات خاص. «Marker» یک پین ساده است.
import SwiftUI;
import MapKit;
struct MarkersMap: View {
@State private var position: MapCameraPosition = .region(
MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090),
span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
)
);
let places = [
("Park", CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090)),
("Cafe", CLLocationCoordinate2D(latitude: 37.3327, longitude: -122.0053))
];
var body: some View {
Map(position: $position) {
ForEach(places, id: \.0) { name, coord in
Marker(name, coordinate: coord);
}
}
}
}
import SwiftUI;
struct ContentView: View {
var body: some View {
MarkersMap();
}
}
import SwiftUI;
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView();
}
}
}
اینجا دو Marker نزدیک هم داریم. یکی پارک است. یکی کافه.
بازکردن مسیر در Apple Maps
با MKMapItem مقصد را می سازیم. سپس مسیر را در Maps باز می کنیم.
import MapKit;
func openDirections() {
let dest = MKMapItem(placemark: MKPlacemark(coordinate: .init(latitude: 37.3349, longitude: -122.0090)));
dest.name = "Apple Park";
dest.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]);
}
import SwiftUI;
struct ContentView: View {
var body: some View {
Button("Open Directions") {
openDirections();
}
.padding();
}
}
import SwiftUI;
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView();
}
}
}
نکته: قبل از استفاده از مکان کاربر، اجازه دسترسی را درخواست کن.
گام های عملی سریع
- 1) ماژول MapKit را ایمپورت کن.
- 2) Region یا CameraPosition بساز.
- 3) Map را با position ببند.
- 4) Marker یا Annotation اضافه کن.
- 5) اگر خواستی، مسیر را در Maps باز کن.
جمع بندی سریع
- نقشه MapKit نمایش نقشه را ساده می کند.
- Annotation پین یا نمای سفارشی است.
- MKMapItem مسیر را در Maps باز می کند.
- مجوز مکان را فراموش نکن.
مطالب مرتبط: URLSession پس زمینه برای دانلود فایل ها، Core Location برای درخواست موقعیت.