💆

【Swift】初めてのSwiftUIで地図検索機能を作る

2024/08/12に公開

地図検索

import SwiftUI
struct ContentView: View {
    
    @State var inputText: String = ""
    @State var displaySearchKey: String = "東京駅"
    var body: some View {
        VStack {
            TextField("キーワード", text: $inputText, prompt: Text("キーワードを入力してください"))
            .onSubmit {
                displaySearchKey = inputText
            }
            .padding()
        }
        MapView(searchKey: displaySearchKey)
    }
}
import SwiftUI
import MapKit

struct MapView: View {
    let searchKey: String
    
    @State var targetCoordinate = CLLocationCoordinate2D()
    @State var cameraPosition: MapCameraPosition = .automatic
    
    var body: some View {
        Map(position: $cameraPosition){
            Marker(searchKey, coordinate: targetCoordinate)
        }
        .onChange(of: searchKey, initial: true) { oldValue, newValue
            in
            let request = MKLocalSearch.Request()
            request.naturalLanguageQuery = newValue
            let search = MKLocalSearch(request: request)
            search.start { response, error in
                if let mapItems = response?.mapItems,
                   let mapItem = mapItems.first {
                   targetCoordinate = mapItem.placemark.coordinate
                   print("\(targetCoordinate)")
                   
                    cameraPosition = .region(MKCoordinateRegion(
                        center : targetCoordinate,
                        latitudinalMeters: 500.0,
                        longitudinalMeters: 500.0
                    ))
                }
            }
        }
    }
}

参考

Image from Gyazo

Discussion