Shawn Wilson Shawn Wilson - 5 months ago 44
iOS Question

Displaying CLLocation in label Xcode 7 Swift 2

hey all i am brand new into coding iOS apps, and find it rather enjoyable so far..

I am having an issue assigning lat and lng to a text field. I have been following along in a tutorial but it crapped out and most examples i have found are in objective C and not swift.. and the ones in swift aren't all the best..

my ViewController is below:

import UIKit
import MapKit

class LocationVC: UIViewController, MKMapViewDelegate {

@IBOutlet weak var map: MKMapView!
@IBOutlet weak var latField: UITextField!
@IBOutlet weak var lngField: UITextField!
@IBOutlet weak var locateBtn: UIButton!
@IBOutlet weak var saveBtn: UIButton!

let regionRadius: CLLocationDistance = 500

let locationManager = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()

map.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}

override func viewDidAppear(animated: Bool) {
locationAuthStatus()
}

func locationAuthStatus() {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
map.showsUserLocation = true
} else {
locationManager.requestWhenInUseAuthorization()
}
}

func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 1, regionRadius * 1)
map.setRegion(coordinateRegion, animated: true)
}

func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
if let loc = userLocation.location {
centerMapOnLocation(loc)
}

let latField = location.longitude
let lngField = location.latitude
}

}


So far the map is moving, works on my device but I have no idea how to get the coords to appear..

Please forgive me if this is a noob question, but I just cant get this damn thing to go..

Answer

Replace your mapView(_ :,didUpdatedUserLocation:) with this...

func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
    if let loc = userLocation.location 
    {
        centerMapOnLocation(loc)

        self.latField.text = "\(loc.coordinate.latitude)"
        self.lngField.text = "\(loc.coordinate.longitude)"
    }
}

Note: If you only need show the lat/lng could be a better idea to use an UILabel instead of UITextFiel