はじめに
昨日に引き続き、iOS17以降のMapKitに関することを調べてみました。
今回はGoogleマップでいう「ストリートビュー」をAppleMapを使用して実装します。
サンプルアプリ
実装
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
}
おわり
これを使えばめっちゃかっこいいアプリが作れそうです
公式ドキュメント