Gowthaman M
Gowthaman M

Reputation: 8272

How to get the address from the coordinate

I want to get the address from the coordinate. I have attached my code below..

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let lastLocation = locations.last!
    let latvalue     = lastLocation.coordinate.latitude
    let lngvalue     = lastLocation.coordinate.longitude
    self.db_latvalue = latvalue
    self.db_lngvalue = lngvalue
    let location = CLLocation(latitude: latvalue, longitude:lngvalue)
    let address = CLGeocoder.init()
    address.reverseGeocodeLocation(CLLocation.init(latitude: latvalue, longitude:lngvalue)) { (places, error) in
        if error == nil{
            if let place = places{
                   print("addressshowingssq \(place)")
                self.db_address = "\(place)"

            }
        }
    }

Output:

[L-30 2nd A Main Road, L-30 2nd A Main Road, HSR Layout, Bengaluru, Karnataka 560102, India @ <+12.91597974,+77.62879254> +/- 100.00m, region CLCircularRegion (identifier:'<+12.91597974,+77.62879254> radius 70.94', center:<+12.91597974,+77.62879254>, radius:70.94m)]

I want only the address as i mention below

L-30 2nd A Main Road, L-30 2nd A Main Road, HSR Layout, Bengaluru, Karnataka 560102

I researched google i got different solution so i got confused.

Upvotes: 2

Views: 2961

Answers (4)

Vinaykrishnan
Vinaykrishnan

Reputation: 768

Swift 3

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let locValue:CLLocationCoordinate2D = manager.location!.coordinate
    let objLocation = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude)
    CLGeocoder().reverseGeocodeLocation(objLocation) { (placemarksArray, error) in
        if error != nil {
            print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
            return
        }
        if (placemarksArray?.count)! > 0 {
            let objPlacemark = placemarksArray?[0]
            self.generateAddress(objPlacemark: objPlacemark!)
            self.locationManager?.stopUpdatingLocation()
            self.locationManager = nil
        }
        else {
            print("Problem with the data received from geocoder")
        }
    }
}

Function Parsing placemark to string...

func generateAddress(objPlacemark : CLPlacemark) -> String {

    print("objPlacemark : \(objPlacemark.description)")
    var completeAddress = ""

    if objPlacemark.name != nil {
        completeAddress = String(describing: objPlacemark.name!)
    }

    if objPlacemark.thoroughfare != nil && (objPlacemark.name != objPlacemark.thoroughfare) {
        completeAddress = completeAddress + ", " + String(describing: objPlacemark.thoroughfare!)
    }

    if objPlacemark.subThoroughfare != nil {
        completeAddress = completeAddress + ", " + String(describing: objPlacemark.subThoroughfare!)
    }

    if objPlacemark.subLocality != nil {
        completeAddress = completeAddress + "," + String(describing: objPlacemark.subLocality!)
    }

    if objPlacemark.locality != nil {
        completeAddress = String(describing: objPlacemark.locality!)
    }

    if objPlacemark.postalCode != nil {
        completeAddress = completeAddress + "," + String(describing: objPlacemark.postalCode!)
    }

    if objPlacemark.administrativeArea != nil {
        completeAddress = completeAddress + "," +  String(describing: objPlacemark.administrativeArea!)
    }

    if objPlacemark.isoCountryCode != nil {
        completeAddress = completeAddress + "," + String(describing: objPlacemark.isoCountryCode!)
    }

    print("completeAddress : \(completeAddress)")
    return completeAddress
}

Upvotes: 1

Rawand Ahmed Shaswar
Rawand Ahmed Shaswar

Reputation: 2561

Update

I have done a few modification to iVarun's solution. This is simpler. and working.

First, add this function:

func geocode(latitude: Double, longitude: Double, completion: @escaping (CLPlacemark?, Error?) -> ())  {
    CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { completion($0?.first, $1) }
}

After that, get the address:

geocode(latitude: latvalue, longitude: lngvalue) { placemark, error in
    guard let placemark = placemark, error == nil else { return }
    // you should always update your UI in the main thread
    DispatchQueue.main.async {
        //  update UI here
        print("address1:", placemark.thoroughfare ?? "")
        print("address2:", placemark.subThoroughfare ?? "")
        print("city:",     placemark.locality ?? "")
        print("state:",    placemark.administrativeArea ?? "")
        print("zip code:", placemark.postalCode ?? "")
        print("country:",  placemark.country ?? "")
    }
}

Result:

address1: Rua Casuarina
address2: 443
city: Rio de Janeiro
state: RJ
zip code: 20975
country: Brazil

As @iOSer indicated, CLPlacemark is capable of giving you this part of the string, However.

You could split the string:

let output:String = "[L-30 2nd A Main Road, L-30 2nd A Main Road, HSR Layout, Bengaluru, Karnataka 560102, India @ <+12.91597974,+77.62879254> +/- 100.00m, region CLCircularRegion (identifier:'<+12.91597974,+77.62879254> radius 70.94', center:<+12.91597974,+77.62879254>, radius:70.94m)]"
let items = output.components(separatedBy: "@")
print(items[0])

Becuse the @ will be always included, you could skip the rest.

Result: R

Upvotes: 7

iVarun
iVarun

Reputation: 6611

Hope this will help you:

address.reverseGeocodeLocation(CLLocation.init(latitude: latvalue, longitude:lngvalue)) { (places, error) in
            if error == nil{
                let placeMark = places! as [CLPlacemark]

                if placeMark.count > 0 {
                    let placeMark = places![0]
                    var addressString : String = ""

                    if placeMark.subThoroughfare != nil {
                        addressString = addressString + placeMark.subThoroughfare! + ", "
                    }
                    if placeMark.thoroughfare != nil {
                        addressString = addressString + placeMark.thoroughfare! + ", "
                    }
                    if placeMark.subLocality != nil {
                        addressString = addressString + placeMark.subLocality! + ", "
                    }

                    if placeMark.locality != nil {
                        addressString = addressString + placeMark.locality! + ", "
                    }
                    if placeMark.administrativeArea != nil {
                        addressString = addressString + placeMark.administrativeArea! + ", "
                    }
                    if placeMark.country != nil {
                        addressString = addressString + placeMark.country! + ", "
                    }
                    if placeMark.postalCode != nil {
                        addressString = addressString + placeMark.postalCode! + " "
                    }

                    print(addressString)
                }
            }
        }

Output:

L-30, 2nd A Main Road, HSR Layout, Bengaluru, Karnataka, India, 560102

Upvotes: 3

iOSer
iOSer

Reputation: 2336

CLGeocodeCompletionHandler contains an array of CLPlacemark. You can access its properties such as name, locality, isoCountryCode etc to form a complete address!!

Upvotes: 0

Related Questions