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

时间:2018-02-09 12:35:21

标签: ios swift mapbox userlocation

我在Swift 4中使用 Mapbox ,当我想显示用户位置时遇到问题。我不明白为什么用户位置没有按原样设置。

我会在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(纬度:-180.0,经度:-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)
        }
    }
}

2 个答案:

答案 0 :(得分:1)

Larme is correct:用户的位置通常在-viewDidLoad中不可用。当用户的位置可用以及更新时,使用-mapView:didUpdateUserLocation:委托方法进行通知。

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

-180, -180是核心位置的kCLLocationCoordinate2DInvalid常量。在尝试在地图上显示CLLocationCoordinate2DIsValid()之前,您通常应该检查CLLocationCoordinate2D

答案 1 :(得分:0)

Sergey Kargopolov对于如何使用CLLocationManager和CLLocationManagerDelegate获取用户位置有great example的信息。这是他的代码:

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)")
}
}