簡體   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