简体   繁体   English

如何在swift中将地图置于用户位置的中心?

[英]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. 我正在编写一个应用程序,我有一个嵌入式mapview来显示用户的位置。 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: 我还在我的plist中添加了两个条目:

NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription

and also in my xcode I have set to emulate the GPS data on london, UK. 而且在我的xcode中,我已经开始在英国伦敦模拟GPS数据。

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: viewDidLoad() ,否则我有错误:

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? 你能帮帮我吗?

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. 代码的问题在于,当用户提供位置权限时,您试图将地图指向用户的位置,而不是等待CoreLocation为您提供实际的用户位置。 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. 您需要使用CLLocationManagerDelegate方法locationManager(_:didUpdateLocations:)当你得到了用户的实际位置通知的,在那里你可以设置映射指向用户的位置。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM