Implementation of 'My Location' button in Swift

DP27 picture DP27 · Jan 31, 2017 · Viewed 10.4k times · Source

I am currently stuck while attempting to figure out how to add a button on my map that will redisplay a user's current location if they stray away from it on the map. At the moment I have the code written below that displays the user's current location.

    import UIKit
    import MapKit
    import CoreLocation

   class GameViewController: UIViewController,CLLocationManagerDelegate
   {

var lastUserLocation: MKUserLocation?





@IBOutlet weak var Map: MKMapView!

let manager = CLLocationManager()





func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[0]

    let span:MKCoordinateSpan = MKCoordinateSpanMake(0.00775, 0.00775)

    let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)

    let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
    Map.setRegion(region, animated: true)


    self.Map.showsUserLocation = true
    manager.stopUpdatingLocation()


}



override func viewDidLoad() {
    super.viewDidLoad()
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestAlwaysAuthorization()
    manager.startUpdatingLocation()




}

@IBAction func refLocation(_ sender: Any) {
    print("click")
}





override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

What I am unsure of, is what code to put inside of the @IBAction function that will allow the map to re-center to the user's current location if they stray from it while looking elsewhere.

Answer

Nirav D picture Nirav D · Jan 31, 2017

For that you can call again startUpdatingLocation method of CLLocationManager on your Button action.

To get the the correct current location of user you need to access the last object from the location array in didUpdateLocations method.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    //Access the last object from locations to get perfect current location
    if let location = locations.last {        
        let span = MKCoordinateSpanMake(0.00775, 0.00775)        
        let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)        
        let region = MKCoordinateRegionMake(myLocation, span)
        Map.setRegion(region, animated: true)
    }               
    self.Map.showsUserLocation = true
    manager.stopUpdatingLocation()                
}

Now simply call startUpdatingLocation on your button action.

@IBAction func refLocation(_ sender: Any) {
    manager.startUpdatingLocation()
}