緯度経度の座標から逆ジオコーディング(リバースジオコーディング)で住所を取得することができます。
これにはGoogleのAPIを利用しますので、GoogleMapsをインポートしている前提でのお話です。
座標をGoogleMapから取得します。
例えばタップであればcoordinate: CLLocationCoordinate2Dが取得できますので
これを元にCLLocationオブジェクトを作成します。
1 | let location: CLLocation = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude) |
逆ジオコーディングを行うメソッド
結果をアラートで表示しています。
1 | func ReverseGeocoder(location: CLLocation) { |
3 | var address: String = "" |
5 | CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error)->Void in |
12 | if placemarks!.count > 0 { |
13 | let pms = placemarks![0] |
14 | address = self.makeAddressString(placemark: pms) |
17 | let aMessage = address |
18 | let alert = UIAlertController(title: aTitle, message: aMessage, preferredStyle: .alert) |
20 | alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) |
22 | self.present(alert, animated: false, completion: nil) |
取得できた住所を一連の文字列に変換するメソッド
1 | func makeAddressString(placemark: CLPlacemark) -> String { |
3 | var address: String = "" |
5 | //address += placemark.postalCode != nil ? placemark.postalCode! : "" |
6 | address += placemark.administrativeArea != nil ? placemark.administrativeArea! : "" |
7 | address += placemark.subAdministrativeArea != nil ? placemark.subAdministrativeArea! : "" |
8 | address += placemark.locality != nil ? placemark.locality! : "" |
9 | address += placemark.subLocality != nil ? placemark.subLocality! : "" |
10 | address += placemark.thoroughfare != nil ? placemark.thoroughfare! : "" |
11 | address += placemark.subThoroughfare != nil ? placemark.subThoroughfare! : "" |
Xcode: 8.3.2
Swift: 3.1
OS: Sierra 10.12