简体   繁体   中英

Swift: Get user's location coordinates as latitude and longitude?

When a user presses a button, I'd like to store their latitude and longitude as variables. I don't understand how to use the Coordinate2D method. Instead of println(locManager.location) I would like to print (or store as separate variables) the latitude and longitude. Please help. My code is below.

class ViewController: UIViewController, CLLocationManagerDelegate {

  var locManager = CLLocationManager()

  @IBOutlet var pushToParkText: UILabel!

  @IBAction func carButton(sender: UIButton) {
    println(locManager.location)
  }

  @IBOutlet var labelLatitude: UILabel!
  @IBOutlet var labelLongitude: UILabel!

  override func viewDidLoad() {
    super.viewDidLoad()

    // Core Location Manager asks for GPS location
    locManager.delegate = self
    locManager.desiredAccuracy = kCLLocationAccuracyBest
    locManager.requestWhenInUseAuthorization()
    locManager.startMonitoringSignificantLocationChanges()

    // Check if the user allowed authorization
    if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse ||
        CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized)
    {       
        println(locManager.location)

        } else {
            labelLatitude.text = "Location not authorized"
            labelLongitude.text = "Location not authorized"
        }
    }
}
let latitude = locManager.location.coordinate.latitude
let longitude = locManager.location.coordinate.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