【问题标题】:Why userLocation returns (-180.0,-180.0) coordinates on Mapbox?为什么 userLocation 在 Mapbox 上返回 (-180.0,-180.0) 坐标?
【发布时间】:2018-09-13 11:06:31
【问题描述】:

我在 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)
        }
    }
}

【问题讨论】:

  • 因为获取位置是异步的?目前还不清楚你到底在做什么。
  • @Larme 我更新了我的问题,好些了吗?

标签: ios swift mapbox userlocation


【解决方案1】:

Larme is correct:用户的位置通常在-viewDidLoad 中不可用。使用-mapView:didUpdateUserLocation: 委托方法在用户位置可用和更新时收到通知。

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      相关资源
      最近更新 更多