为什么UserLocation返回(-180.0,-180.0)在MAPBOX上坐标



i使用 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)

但我明白了:

cllocation coortion2d(纬度:-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)
        }
    }
}

larme是正确的:用户的位置通常在-viewDidLoad中尚不可用。使用-mapView:didUpdateUserLocation:委托方法在用户的位置可用以及更新时通知。

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

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

Sergey Kargopolov有一个很好的例子,说明了如何使用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)")
}
}

相关内容

  • 没有找到相关文章

最新更新