LoginSignup
0
2

More than 3 years have passed since last update.

新しいmapを使ってみた

Last updated at Posted at 2020-08-14

はじめに

Apple Developer DocumentationをみるとMapKit中にstruct Mapが増えています。
どうもSwiftUIで直接mapが表示できるようになったようです。
実際に作ってみました。
サンプルプロジェクトはgithubにアップしてあります。

コードの解説

サンプルプロジェクトのポイントを紹介します。

Mapを表示する

@State var coordinate = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 36.0, longitude: 138), latitudinalMeters: 2000000, longitudinalMeters: 2000000)
Map(coordinateRegion: $coordinate)

Mapを表示するには、表示したい位置情報(coordinate)を指定すると表示できます。

ピンを表示する

ピンを表示するには、MapAnnotationProtocolを実装する必要があるようです。
今回は、下記のような構造体を用意しました。(ネーミングが悪くてすみません)

struct AnnotationItemStruct:Identifiable{
    // ID(識別子)
    let id = UUID()
    // 緯度経度
    let coordinate:CLLocationCoordinate2D
}

次にピンの配列を作成します。

@State var annotationItems: [AnnotationItemStruct] = []

最後にピンに位置情報を追加します。

let annotationItem = AnnotationItemStruct(coordinate: coordinate)
self.annotationItems.append(annotationItem)

実際にピンをmapに表示できるようにmapを修正します。

Map(coordinateRegion: $coordinate, annotationItems: annotationItems) { annotationItem in
    // annotationItemsから1つ取りだした情報からピンを打つ
    MapPin(coordinate: annotationItem.coordinate)
}

参考

0
2
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
0
2