我正在尝试显示从用户当前位置到某个位置的大致旅行时间,并且地图上已经显示方向。我想知道这是否可能,因为当我搜索这个时,网上似乎没有出现任何东西。如果可能的话,swift会比Objective-C更好。
您已经在地图上显示方向,并且您的要求是使用Apple地图。我认为您正在使用MKDirectionsRequest
来获取和显示方向。使用MKDirectionsRequest
您可以找到方向和可能的路线。您可以指定所需的方向类型(汽车、公交、步行(,并从route
获取估计的旅行时间。为了您的方便,我添加了完整的代码。
let request = MKDirectionsRequest()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: startLocation?.latitude, longitude: startLocation?.longitude), addressDictionary: nil))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: endLocation?.latitude, longitude: endLocation?.longitude), addressDictionary: nil))
request.requestsAlternateRoutes = true // if you want multiple possible routes
request.transportType = .automobile // will be good for cars
现在获取方向
let directions = MKDirections(request: request)
directions.calculate {(response, error) -> Void in
guard let response = response else {
if let error = error {
print("Error: (error)")
}
return
}
// Lets Get the first suggested route and its travel time
if response.routes.count > 0 {
let route = response.routes[0]
print(route.expectedTravelTime) // it will be in seconds
// you can show this time in any of your UILabel or whatever you want.
}
}