Convert GPS coordinates to a city name / address in Swift
Asked Answered
V

4

7

I have a latitude/longitude location that I want to convert to the location name String in Swift. What is the best way to do this? i believe it's best to use the reverseGeocodeLocation function but not exactly sure how to. This is what I have so far:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    if (locationFixAchieved == false) {
        locationFixAchieved = true
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation
        var coord = locationObj.coordinate
        var latitude = coord.latitude
        var longitude = coord.longitude

        getCurrentWeatherData("\(longitude)", latitude: "\(latitude)")
        reverseGeocodeLocation(location:coord, completionHandler: { (<#[AnyObject]!#>, <#NSError!#>) -> Void in
            <#code#>
        })

    }
}

func reverseGeocodeLocation(location: CLLocation!, completionHandler: CLGeocodeCompletionHandler!){

}
Volumed answered 6/10, 2014 at 23:56 Comment(1)
Attached what I've attempted. i think I have to use reverseGeocodeLocation function but not sure how toVolumed
C
13

You need to write the code like this:

geocoder.reverseGeocodeLocation(currentLocation, completionHandler: {
            placemarks, error in

                if error == nil && placemarks.count > 0 {
                    self.placeMark = placemarks.last as? CLPlacemark
                    self.adressLabel.text = "\(self.placeMark!.thoroughfare)\n\(self.placeMark!.postalCode) \(self.placeMark!.locality)\n\(self.placeMark!.country)"
                    self.manager.stopUpdatingLocation()
                }
            })
Compotation answered 7/10, 2014 at 8:32 Comment(1)
I would just add that intead of appending all the placemark components, you can just use : self.adressLabel.text = ABCreateStringWithAddressDictionary(self.placemark.addressDictionary!, false) for <= iOS 8 from the AdressBookUI framework and CNPostaAddressFormatter from the Contacts framework for > iOS 9.0Habitable
T
5

I am using Swift 3 / XCode 8

I used Benjamin Herzog's answer but I ran into some build errors related to optional and casting.

In rewriting it, I decided to encapsulate it in a function and generalize it so it can easily be plugged in anywhere.

import CoreLocation

func getPlacemark(forLocation location: CLLocation, completionHandler: @escaping (CLPlacemark?, String?) -> ()) {
    let geocoder = CLGeocoder()

    geocoder.reverseGeocodeLocation(location, completionHandler: {
        placemarks, error in

        if let err = error {
            completionHandler(nil, err.localizedDescription)
        } else if let placemarkArray = placemarks {
            if let placemark = placemarkArray.first {
                completionHandler(placemark, nil)
            } else {
                completionHandler(nil, "Placemark was nil")
            }
        } else {
            completionHandler(nil, "Unknown error")
        }
    })

}

Using it:

getPlacemark(forLocation: originLocation) { 
    (originPlacemark, error) in
        if let err = error {
            print(err)
        } else if let placemark = originPlacemark {
            // Do something with the placemark
        }
    })
}
Tsushima answered 4/10, 2016 at 21:5 Comment(0)
A
4

please check this answer.

 func getAddressFromGeocodeCoordinate(coordinate: CLLocationCoordinate2D) {
    let geocoder = GMSGeocoder()
    geocoder.reverseGeocodeCoordinate(coordinate) { response , error in

      //Add this line
      if let address = response!.firstResult() {
        let lines = address.lines! as [String]
        print(lines)

      }
    }
  }
Aprilaprile answered 19/4, 2016 at 14:58 Comment(0)
J
0

Swift Code to get address of the placemark, nicely Formatted

let address = ABCreateStringWithAddressDictionary(placemark.addressDictionary!, false).componentsSeparatedByString("\n").joinWithSeparator(", ")

print(address!)
Jungle answered 12/7, 2016 at 10:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.