繁体   English   中英

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

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

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

我已经实现了似乎是正确的代码,但userLat(纬度)和userLon(经度)的值是关闭的。

NB有人和我有同样的问题,但他的答案从未得到解决: 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 (目标C中的MGLUserTrackingModeFollow )。 当位置可用时,这将自动移动地图。

你看到MGLMapView.userLocation伪造数字的MGLMapView.userLocation是用户的位置通常在viewDidLoad不可用。 使用mapView:didUpdateUserLocation: delegate方法,在用户的位置可用时以及更新时通知。

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

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

暂无
暂无

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

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