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

烈酒焚心 提交于 2020-02-03 04:49:09

问题


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?


回答1:


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)
    }
}


来源:https://stackoverflow.com/questions/35685006/how-i-can-center-the-map-on-users-location-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!