Swift リバースジオコーディングを利用する

個人開発したアプリの宣伝
目的地が設定できる手帳のような使い心地のTODOアプリを公開しています。
Todo with Location

Todo with Location

  • Yoshiko Ichikawa
  • Productivity
  • Free

スポンサードリンク

CLGeocoderを使うと、緯度経度から簡単にReverse Geocodingすることができる。

Reverse Geocodingの実装

処理は非同期で行うので、完了後のコールバックメソッドに処理結果を引数としたクロージャーを利用すれば応用がきく。

import CoreLocation

class MyLocation: NSObject{

    func reverseGeocode(lat: Double, lon: Double, complete:@escaping (_ o:[CLPlacemark])->Void){
        let location = CLLocation(latitude: lat, longitude: lon)
        let geocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(location) { (placemark, Error) in
            guard let placemarks = placemark else{
                return
            }
            complete(placemarks)
        }
    }
}


住所データの取り出し

日本圏内の住所の取得は以下のような記述で取り出せる。

let myLocation = MyLocation()
myLocation.reverseGeocode(lat: 35.653948476390205, lon: 139.73154725662124) { (placemarks) in
    if let data = placemarks.first {
        print(data.country)  //国
        print(data.administrativeArea) //都道府県
        print(data.subAdministrativeArea) //郡部
        print(data.locality) //市区町村
        print(data.subLocality) //町名、字
        print(data.thoroughfare) //町名 + 丁目、番
        print(data.subThoroughfare) //番地 + 号
    }
}


サンプル

東京23区

country:日本
administrativeArea:東京都
subAdministrativeArea:
locality:千代田区
subLocality:麹町
thoroughfare:麹町4丁目
subThoroughfare:1

政令指定都市

country:日本
administrativeArea:大阪府
subAdministrativeArea:
locality:大阪市北区
subLocality:梅田
thoroughfare:梅田2丁目
subThoroughfare:4番43号

市部

country:日本
administrativeArea:東京都
subAdministrativeArea:
locality:日野市
subLocality:南平
thoroughfare:南平7丁目
subThoroughfare:2番12号

郡部

country:日本
administrativeArea:高知県
subAdministrativeArea:高岡郡
locality:高岡郡日高村
subLocality:本郷
thoroughfare:本郷33
subThoroughfare: