简体   繁体   中英

Can I get the user longitude and latitude from their address in Swift?

As the title says, I am trying to derive the user's location from their address as they input in into the app however I have not found any way to do this. I would really appreciate it if someone could help me. Thanks!

Here is a function that you can use to get location from address

func getLocation(from address: String, completion: @escaping (_ location: CLLocationCoordinate2D?)-> Void) {
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(address) { (placemarks, error) in
        guard let placemarks = placemarks,
        let location = placemarks.first?.location?.coordinate else {
            completion(nil)
            return
        }
        completion(location)
    }
}

So let's say if i have this address:

let address = "1 Infinite Loop, Cupertino, CA 95014"

Usage

getLocation(from: address) { location in
    print("Location is", location.debugDescription)
    // Location is Optional(__C.CLLocationCoordinate2D(latitude: 39.799372, longitude: -89.644458))

   print(location.latitude) // result 39.799372
   print(location.longitude) // result -89.644458


}

We can get the coordinate from the below code,

import UIKit
import CoreLocation


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        getCoordinatesFromPlace(place: "1 Infinite Loop, Cupertino, CA 95014")
    }

    func getCoordinatesFromPlace(place: String){

        let geoCoder = CLGeocoder()
        geoCoder.geocodeAddressString(place) { (placemarks, error) in
            guard
                let placemarks = placemarks,
                let location = placemarks.first?.location?.coordinate
            else {
                // handle no location found
                return
            }
            print(location.latitude)
            print(location.longitude)

        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM