【发布时间】:2018-09-13 11:06:31
【问题描述】:
我在 Swift 4 中使用 Mapbox,但当我想显示用户位置时遇到了问题。我不明白为什么用户位置没有按应有的设置。
我会在viewDidLoad() 方法中获取用户位置坐标。为此,我在 ViewController 声明中设置了 MGLMapViewDelegate 和 CLLocationManagerDelegate。然后,在我的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