自分用の時刻表アプリを作ろう、という記事を書いた時に、乗り場をタップすると、その乗り場の地図を表示できたらいいなと思ったので、調べました。
以下、調布駅北口ロータリー周辺の地図を表示し、12番乗り場にピンを立てるコードです。
import SwiftUI
import MapKit
// ピンを定義する構造体
struct identifiableplace: Identifiable {
let id = UUID()
let latitude: Double
let longitude: Double
var coordinate: CLLocationCoordinate2D {
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
struct ContentView: View {
// 12番乗り場
let terminal12 = [
identifiableplace(latitude: 35.652148, longitude: 139.543785)
]
// 調布駅北口のロータリー周辺
@State private var region =
MKCoordinateRegion(
center: .init(latitude: 35.65249,
longitude: 139.54409),
latitudinalMeters: 120,
longitudinalMeters: 120
)
var body: some View {
Map(coordinateRegion: $region,
annotationItems: terminal12,
annotationContent: { spot in MapPin(coordinate: spot.coordinate, tint: .red)
}).edgesIgnoringSafeArea(.all)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
AppleのMapKitのドキュメントを参考にしました。ピンだけでなく、マーカーやアノテーションの説明があります。
https://developer.apple.com/documentation/mapkit/map
以下の環境で、動作を確認しました。
MacOS Monterey 12.5.1
Xcode 13.4.1