为什么 userLocation returns (-180.0,-180.0) 坐标在 Mapbox 上?

Why userLocation returns (-180.0,-180.0) coordinates on Mapbox?

我使用 Mapbox 和 Swift 4,当我想显示用户位置时遇到问题。我不明白为什么没有按应有的方式设置用户位置。

我会在 viewDidLoad() 方法中获取用户位置坐标。为此,我在 ViewController 声明中设置了 MGLMapViewDelegateCLLocationManagerDelegate。然后,在我的 viewDidLoad() 中我有:

// Mapview configuration
let mapView = MGLMapView(frame: self.mapView.bounds)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.showsUserLocation = true
mapView.setUserTrackingMode(.follow, animated: true)
mapView.delegate = self

self.mapView.addSubview(mapView)

// User location        
print("User location:")
print(mapView.userLocation!.coordinate)

但我明白了:

CLLocationCoordinate2D(latitude: -180.0, longitude: -180.0)

我认为是因为加载视图时未设置位置,但我需要在 viewDidLoad() 中获取值。

我该怎么办,为什么行 mapView.userLocation!.coordinate 不起作用?


编辑

事实上,我想使用 MapboxDirections 在地图上显示用户位置和固定点之间的一条线。为此,我使用此代码 (参见第一条评论):

let waypoints = [
    // HERE I would use the user location coordinates for my first Waypoint
    Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.9131752, longitude: -77.0324047), name: "Mapbox"),
    Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), name: "White House"),
        ]
let options = RouteOptions(waypoints: waypoints, profileIdentifier: .automobileAvoidingTraffic)
options.includesSteps = true

_ = directions.calculate(options) { (waypoints, routes, error) in
    guard error == nil else {
        print("Error calculating directions: \(error!)")
        return
    }

    if let route = routes?.first, let leg = route.legs.first {
        print("Route via \(leg):")

        let distanceFormatter = LengthFormatter()
        let formattedDistance = distanceFormatter.string(fromMeters: route.distance)

        let travelTimeFormatter = DateComponentsFormatter()
        travelTimeFormatter.unitsStyle = .short
        let formattedTravelTime = travelTimeFormatter.string(from: route.expectedTravelTime)

        print("Distance: \(formattedDistance); ETA: \(formattedTravelTime!)")

        if route.coordinateCount > 0 {
            // Convert the route’s coordinates into a polyline.
            var routeCoordinates = route.coordinates!
            let routeLine = MGLPolyline(coordinates: &routeCoordinates, count: route.coordinateCount)

            // Add the polyline to the map and fit the viewport to the polyline.
            mapView.addAnnotation(routeLine)
            mapView.setVisibleCoordinates(&routeCoordinates, count: route.coordinateCount, edgePadding: .zero, animated: true)
        }
    }
}

: the user's location typically isn't available yet in -viewDidLoad. Use the -mapView:didUpdateUserLocation: 委托方法在用户位置可用和更新时得到通知。

如果您在显示地图之前需要用户的位置,请考虑 运行 您自己的 CLLocationManager

-180, -180 是来自 Core Location 的 kCLLocationCoordinate2DInvalid 常量。在尝试在地图上显示 CLLocationCoordinate2D 之前,您通常应该检查是否 CLLocationCoordinate2DIsValid()

Sergey Kargopolov great example 介绍了如何使用 CLLocationManager 和 CLLocationManagerDelegate 获取用户位置。这是他的代码:

class ViewController: UIViewController, CLLocationManagerDelegate {

var locationManager:CLLocationManager!

override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    determineMyCurrentLocation()
}


func determineMyCurrentLocation() {
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.startUpdatingLocation()
        //locationManager.startUpdatingHeading()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation:CLLocation = locations[0] as CLLocation

    // Call stopUpdatingLocation() to stop listening for location updates,
    // other wise this function will be called every time when user location changes.

   // manager.stopUpdatingLocation()

    print("user latitude = \(userLocation.coordinate.latitude)")
    print("user longitude = \(userLocation.coordinate.longitude)")
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
    print("Error \(error)")
}
}