Search code examples
swiftxcodegeocodingreversecllocation

Converting CLLocationCoordinate2d to Street Address with Swift


Im trying to convert CLLocationCoordinates2d coordinates to a physical street address.

I have tried CLGeocoder with no luck. Here is my code that supplies the latitude and longitude coordinates.

    let manager = CLLocationManager()

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{

    guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    print("locations = \(locValue.latitude) \(locValue.longitude)")
    // let locationtext = "locations = \(locValue.latitude) \(locValue.longitude)"
    locationTxt.text = "\(locValue.latitude) \(locValue.longitude)"

}

Thank you!


Solution

  • func convertLatLongToAddress(latitude:Double,longitude:Double){
        
        let geoCoder = CLGeocoder()
        let location = CLLocation(latitude: latitude, longitude: longitude)
        geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
            
            // Place details
            var placeMark: CLPlacemark!
            placeMark = placemarks?[0]
            
            // Location name
            if let locationName = placeMark.location {
                print(locationName)
            }
            // Street address
            if let street = placeMark.thoroughfare {
                print(street)
            }
            // City
            if let city = placeMark.locality {
                print(city)
            }
            // State
            if let state = placemark.administrativeArea {
                print(state)
            }
            // Zip code
            if let zipCode = placeMark.postalCode {
                print(zipCode)
            }
            // Country
            if let country = placeMark.country {
                print(country)
            }
        })
        
    }