Home > Blockchain >  how to get lat, lng by using geocoder
how to get lat, lng by using geocoder

Time:11-24

import CoreLocation

func ConvertAddress(address: String) -> [Double] {
    let geocoder = CLGeocoder()
    var lat: Double = 0
    var lng: Double = 0
    geocoder.geocodeAddressString(address) { placemarks, error in
        let placemark = placemarks?.first
        lat = placemark?.location?.coordinate.latitude ?? 0
        lng = placemark?.location?.coordinate.longitude ?? 0
    }
    return [lat, lng]
}

ConvertAddress(address: "서원구 수곡로 57번길 32-2(수곡동)")

I checked result has right lat, lng value. But when i use return, using func the values are [0,0] How can i get lat, lng?

CodePudding user response:

You are mixing asynchronous code with synchronous code. You need a completion hander or to use the concurrent (async await) option.

Right now the return line runs before the placemark code.

Option 1

func convertAddress(address: String, completionHander: @escaping ([Double]) -> Void) {
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(address) { placemarks, error in
        let placemark = placemarks?.first
        let lat = placemark?.location?.coordinate.latitude ?? 0
        let lng = placemark?.location?.coordinate.longitude ?? 0
        completionHander([lat, lng])
    }
    
}

convertAddress(address: "서원구 수곡로 57번길 32-2(수곡동)") { values in
    print(values)
}

Option 2

func convertAddress(address: String) async throws -> [Double] {
    let geocoder = CLGeocoder()
    let placemarks = try await geocoder.geocodeAddressString(address)
    let placemark = placemarks.first
    let lat = placemark?.location?.coordinate.latitude ?? 0
    let lng = placemark?.location?.coordinate.longitude ?? 0
    return [lat, lng]
}

Task{
    let values = try await convertAddress(address: "서원구 수곡로 57번길 32-2(수곡동)")
    print(values)
}
  • Related