我应该如何在 Mapbox for iOS SDK 中使用 userLocation 找到正确的位置数据? (Swift)

How should I find the correct location data using userLocation in Mapbox for iOS SDK? (Swift)

我正在尝试查找用户位置的纬度和经度,以便我可以在 viewdidload 中以用户为中心放置地图。

我已经实现了看似正确的代码,但 userLat(纬度)和 userLon(经度)的值有很大偏差。

N.B。其他人和我有同样的问题,但他的回答从未得到解决: Mapbox iOS8 Swift mapView.showUsersLocation

import Mapbox

class ViewController: UIViewController, MGLMapViewDelegate, CLLocationManagerDelegate {

//    let locationManager = CLLocationManager()

    @IBOutlet weak var mapView: MGLMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Initalise map's center coordinate as vancouver
        mapView.setCenterCoordinate(CLLocationCoordinate2D(latitude: 49.283382,
            longitude: -123.117394),
            zoomLevel: 15, animated: false)
        view.addSubview(mapView)

        // Set the delegate property of our map view to self after instantiating it.
        mapView.delegate = self

        // User location
        mapView.showsUserLocation = true

        let userLoc = mapView.userLocation!
        userLoc.title = "Hello"
        userLoc.subtitle = "I am here!"

        let userLat = userLoc.coordinate.latitude
        let userLon = userLoc.coordinate.longitude

        print(userLat, userLon)

        /*
        self.locationManager.requestAlwaysAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }*/

    }

    func mapView(mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        return true
    }

}

结果打印:

3.40282346638529e+38 3.40282346638529e+38

奇怪的是注释工作正常,当我点击我的位置时,我得到了标题和副标题。

将地图以用户位置为中心的最简单方法是设置 MGLMapView.userTrackingMode = .follow(Objective C 中的 MGLUserTrackingModeFollow)。这将在位置可用时自动移动地图。

您看到 MGLMapView.userLocation 的虚假号码的原因是用户的位置通常在 viewDidLoad 中尚不可用。使用 mapView:didUpdateUserLocation: 委托方法在用户位置可用和更新时收到通知。

有一个名为 mapViewDidFinishLoadingMap 的委托方法。在此方法中将地图的中心设置为用户坐标。

func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) {
    mapView.setCenter((mapView.userLocation?.coordinate)!, animated: false)
}