LoginSignup
4
1

【SwiftUI】MapKitでストリートビューのような機能を使用する

Posted at

はじめに

昨日に引き続き、iOS17以降のMapKitに関することを調べてみました。

今回はGoogleマップでいう「ストリートビュー」をAppleMapを使用して実装します。

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2023-11-28 at 22.08.56.gif

実装

import SwiftUI
import MapKit

struct ContentView: View {
    // 東京駅の座標
    @State private var position: MapCameraPosition = .region(.init(
        center: .init(latitude: 35.681236, longitude: 139.767125),
        span: .init(latitudeDelta: 0.005, longitudeDelta: 0.005)
    ))

    @State private var lookAroundScene: MKLookAroundScene?

    @State private var isPresentedLookAroundPreview = false

    var body: some View {
        MapReader { mapProxy in
            Map(position: $position)
                .onTapGesture { location in
                    guard let selectedLocation = mapProxy.convert(location, from: .local) else { return }
                    requestLookAroundScene(selectedLocation: selectedLocation)
                    isPresentedLookAroundPreview = true
                }
        }
        .lookAroundViewer(isPresented: $isPresentedLookAroundPreview, scene: $lookAroundScene)
    }

    func requestLookAroundScene(selectedLocation: CLLocationCoordinate2D) {
        Task {
            let request = MKLookAroundSceneRequest(coordinate: selectedLocation)
            lookAroundScene = try? await request.scene
        }
    }
}

解説

今回使用されている新しい技術は3つです

1つ目はMapReaderです。
MapReaderの中にMapを入れてonTapGestureを実装するとタップした位置の座標が取れます。

MapReader { mapProxy in
    Map(position: $position)
        .onTapGesture { location in
            let selectedLocation = mapProxy.convert(location, from: .local)
        }
}

2つ目はlookAroundViewerです。
ここがストリートビューを表示している部分です。

.lookAroundViewer(isPresented: $isPresentedLookAroundPreview, scene: $lookAroundScene)

3つ目はMKLookAroundSceneRequestです。
ここでLookAroundで使えるデータの型に変換してます。

Task {
    let request = MKLookAroundSceneRequest(coordinate: selectedLocation)
    lookAroundScene = try? await request.scene
}

おわり

これを使えばめっちゃかっこいいアプリが作れそうです

公式ドキュメント

4
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
4
1