2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[SwiftUI]住所から地図を表示

Posted at

コード

住所から緯度・経度を取得し、その緯度・経度を基に地図を表示する処理を実装
※ プレビュー で 東京都千代田区千代田 の地図を表示している

import SwiftUI
import MapKit

struct MapView: View {
    let address: String
    @State private var map = MKCoordinateRegion()
    
    var body: some View {
        VStack {
            Map(coordinateRegion: $map)
                .onAppear {
                    self.getLocation(address: address){ location in
                        self.setMap(CLLocationCoordinate2D(latitude: location[0], longitude: location[1]))
                    }
                }
        }
    }
    
    private func getLocation(address: String,completion:@escaping ([CLLocationDegrees]) -> Void){
        CLGeocoder().geocodeAddressString(address) { placemarks, error in
            guard let latitude = placemarks?.first?.location?.coordinate.latitude else { return }
            guard let longitude = placemarks?.first?.location?.coordinate.longitude else { return }
            print("DEBUG: latitude : \(latitude)")
            print("DEBUG: logitude : \(longitude)")
            completion([latitude,longitude]) // 緯度・経度の情報をクロージャで渡す
        }
    }
    
    private func setMap(_ coordinate: CLLocationCoordinate2D){
        self.map = MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
    }
}

struct MapvView_Previews: PreviewProvider {
    static var previews: some View {
        MapView(address: "東京都千代田区千代田")
    }
}

使用方法
SampleView という画面に、地図を表示させている

import SwiftUI

struct SampleView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("地図")
                .padding()
            MapView(address: "東京都千代田区千代田") // 引数に表示したい場所の住所を指定
                .frame(height: 300)
        }
    }
}

struct SampleView_Previews: PreviewProvider {
    static var previews: some View {
        SampleView()
    }
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?