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 1 year has passed since last update.

【SwiftUI】座標から都道府県名を取得する

Posted at

はじめに

座標で記述された場所を人間が読める住所または地名に変換するプロセスを逆ジオコーディングというらしいです。
今回はその逆ジオコーディングをSwiftで行います。

実装

import SwiftUI
import MapKit

struct ContentView: View {
    @State private var administrativeArea: String?
    var body: some View {
        Text(administrativeArea ?? "取得中")
            .task {
                self.administrativeArea = await fetchAdministrativeAreaFromLocation(location: .init(latitude: 35.61311498476422, longitude: 140.11382960595478))
            }
    }
    
    private func fetchAdministrativeAreaFromLocation(location: CLLocation) async -> String? {
        let location = CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let geocoder = CLGeocoder()
        return await reverseGeocodeLocationWithGeocoder(geocoder, location)
    }

    private func reverseGeocodeLocationWithGeocoder(_ geocoder: CLGeocoder, _ location: CLLocation) async -> String? {
        await withCheckedContinuation { continuation in
            geocoder.reverseGeocodeLocation(location) { placemarks, _ in
                continuation.resume(returning: placemarks?.first?.administrativeArea)
            }
        }
    }
}

今回は千葉駅の座標を使用します
35.61311498476422,140.11382960595478

千葉県と表示されました
simulator_screenshot_1CA485B0-AFD0-4BB8-BDD5-350CA185412A.png

おわり

MapKitを使用することで簡単に座標から都道府県名を取得することができました

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?