1
1

More than 1 year has passed since last update.

SwiftUI: Mapを表示してピンを立てる

Last updated at Posted at 2022-08-28

自分用の時刻表アプリを作ろう、という記事を書いた時に、乗り場をタップすると、その乗り場の地図を表示できたらいいなと思ったので、調べました。

以下、調布駅北口ロータリー周辺の地図を表示し、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()
    }
}

こんなかんじで表示されます。
スクリーンショット 2022-08-28 11.00.23.png

AppleのMapKitのドキュメントを参考にしました。ピンだけでなく、マーカーやアノテーションの説明があります。
https://developer.apple.com/documentation/mapkit/map

以下の環境で、動作を確認しました。
MacOS Monterey 12.5.1
Xcode 13.4.1

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1