Search code examples
iosswiftlocationclgeocoder

Cannot save the longitute and latitude from CLGeocoder()


I want to retrieve the longitute and latitude using an address as a string. I found this very useful post here: Convert address to coordinates swift

But when I want to save the results in a double field and return it I can't. What I have done is

func getLatitude(address:String) -> Double{

var lati = 0.0

var geocoder = CLGeocoder()
geocoder.geocodeAddressString("your address") {
    placemarks, error in
    let placemark = placemarks?.first
    if let lat = placemark?.location?.coordinate.latitude{
    lati = lat
    }

   }
  }
 return lati
}

Inside the geocoder.geocodeAddressString block the value is populated but when I try to return it always gives me 0.0 and I have tried everything. Any ideas please?

If it try to print the value inside the inner block of code it gets printed but I can never return it.

Thank you in advance for the answers.


Solution

  • CLLocationCoordinate2D is struct of latitude and longitude both defined as CLLocationDegrees which itself is a typealias of Double.

    var latitude: Double?
    var longitude: Double?
    
    func getLocation(address: String) {
    
        let geocoder = CLGeocoder()
        geocoder.geocodeAddressString(address) { placemarks, error in
            guard let placemark = placemarks?.first else { return }
            let coordinate = placemark.location?.coordinate
            latitude = coordinate?.latitude
            longitude = coordinate?.longitude
        }
    
    }