0

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.

Newboz
  • 69
  • 6

1 Answers1

0

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
    }

}
krbiz
  • 363
  • 3
  • 12
  • Thank you so much for your answer. I will try it and get back to you – Newboz Apr 06 '20 at 17:55
  • I still cannot extract them. I can print the coordinates as I could before inside this block of code but I cannot extract them into a double. – Newboz Apr 07 '20 at 09:17
  • i am calling the function in a button the first time i press it says the latitude is nil and gives me this 2020-04-08 14:09:44.759923+0200 Project[19601:205223] libMobileGestalt MobileGestalt.c:1647: Could not retrieve region info The scond time i press it and after it gives me the correct value Again thanks for your efforts – Newboz Apr 08 '20 at 12:11
  • When you download some image from Internet, it takes some time, right? You can't press button and get the image immediately. Your app sends request first, and after some time takes respond from server. The same situation is here. Geocoder sends request and after some time takes respond with location. So you have to process your data inside of closure. – krbiz Apr 08 '20 at 13:50