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

9
我正在尝试找到用户位置的纬度和经度,以便在viewdidload中将地图居中于用户。
我已经实现了似乎是正确的代码,但userLat(纬度)和userLon(经度)的值相差很大。
请注意,有人和我遇到了同样的问题,但他的答案从未解决: 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

奇怪的是,注释功能正常,当我点击我的位置时,我可以看到标题和副标题。
2个回答

17

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

您看到MGLMapView.userLocation显示虚假数字的原因是用户的位置通常在viewDidLoad中还没有准备好。使用mapView:didUpdateUserLocation:委托方法,在用户位置可用和更新时收到通知。


8

有一个名为mapViewDidFinishLoadingMap的代理方法。在该方法中将地图的中心设置为用户坐标。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接