Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can center the map on user's location in swift?

I'm writing an app and I have an embedded mapview to show user's his location. This is my code so far:

class YourCurrentLocation: UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var mapView: MKMapView!

    var locationManager = CLLocationManager()
    let regionRadius: CLLocationDistance = 1000

    func checkLocationAuthorizationStatus() {
        if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
            mapView.showsUserLocation = true
            centerMapOnLocation(locationManager.location!, map: mapView, radius: regionRadius)
        } else {
            locationManager.requestAlwaysAuthorization() //requestWhenInUseAuthorization()
        }
    }



    func centerMapOnLocation(location: CLLocation, map: MKMapView, radius: CLLocationDistance) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
            radius * 2.0, radius * 2.0)
        map.setRegion(coordinateRegion, animated: true)
    }


    override func viewDidLoad() {
        super.viewDidLoad()

       // mapView.delegate = self


        if CLLocationManager.locationServicesEnabled()
        {
            //locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.requestAlwaysAuthorization()
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
            print("location enabled")
            checkLocationAuthorizationStatus()            
        }
        else
        {
            print("Location service disabled");
        }


        // Do any additional setup after loading the view.
    }

}

I also added the two entries to my plist:

NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription

and also in my xcode I have set to emulate the GPS data on london, UK.

When I run the app - I see the map, but london is not marked. What am I doing wrong?

Btw, I had to comment out this line:

//mapView.delegate = self

in viewDidLoad(), otherwise I had the error:

Cannot assign value of type YourCurrentLocation to type MKMapViewDelegate

and I'm not sure if that's a part of the problem here.

I want to achieve the effect when I display to the user map and a point marked on that map with his location. Can you help me with that?

like image 494
user3766930 Avatar asked Feb 28 '16 16:02

user3766930


People also ask

How do I ask a user for location in Swift?

You need to add a key NSLocationWhenInUseUsageDescription in yours info. plist file and in the value you write something that you want to show the user in the popup dialog. You need to test it on a real device cause Simulator accepts only custom locations. Select the Simulator -> Debug -> Location -> Custom Location...

What is CLLocationManager in Swift?

The object that you use to start and stop the delivery of location-related events to your app.


1 Answers

The problem with your code is that you're trying to point the map to the user's location when the user gives location permission, you're not waiting for the CoreLocation to give you the actual user location. You need to use the CLLocationManagerDelegate method locationManager(_:didUpdateLocations:) to be notified of when you get the user's actual location, and there you can set the map to point to the user's location.

class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet var mapView: MKMapView!
    var locationManager: CLLocationManager?

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager = CLLocationManager()
        locationManager!.delegate = self

        if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
            locationManager!.startUpdatingLocation()
        } else {
            locationManager!.requestWhenInUseAuthorization()
        }
    }

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {


        switch status {
        case .NotDetermined:
            print("NotDetermined")
        case .Restricted:
            print("Restricted")
        case .Denied:
            print("Denied")
        case .AuthorizedAlways:
            print("AuthorizedAlways")
        case .AuthorizedWhenInUse:
            print("AuthorizedWhenInUse")
            locationManager!.startUpdatingLocation()
        }
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let location = locations.first!
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500)
        mapView.setRegion(coordinateRegion, animated: true)
        locationManager?.stopUpdatingLocation()
        locationManager = nil
    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("Failed to initialize GPS: ", error.description)
    }
}
like image 112
paulvs Avatar answered Oct 02 '22 07:10

paulvs