【问题标题】:Can I get the approximated travel time from directions I already have on a mapView?我可以从我已经在 mapView 上获得的方向获得大致的旅行时间吗?
【发布时间】:2019-04-09 02:36:47
【问题描述】:

我正在尝试显示从用户当前位置到地图上已显示路线的位置的大致行程时间。我想知道这是否可能,因为当我搜索此内容时,似乎没有任何内容出现在网上。如果可能的话,swift 会比 Objective-C 更好。

【问题讨论】:

  • 不,你不能,因为旅行时间取决于旅行速度和旅行距离。您可以找到到目的地的距离,以便更新到达时间。
  • 如果我要找到旅行距离,我能找到预计的旅行时间吗?
  • 我想你可以用CLLocationManager估计当前的行驶速度。但我从来没有为自己做过。所以我不能肯定地说是或否。
  • 大概的旅行时间是多少?例如步行、汽车、火车?如果你知道速度,你可以找出估计的时间。 (Objective-C/Swift 应该不是问题)我认为 google 也提供了一些 API 支持来计算时间,如果你想使用他们的 API,你可以检查一下。 developers.google.com/maps/documentation/directions/start
  • 我主要想知道开车的速度。有没有办法用苹果地图代替谷歌?

标签: ios swift mapkit core-location


【解决方案1】:

您已经在地图上显示了路线,并且您的要求是使用 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. 
            }
        }

【讨论】:

  • 非常感谢!这真的很好用!没想到这么简单!
  • 很高兴为您提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-12
  • 2011-09-04
  • 2016-10-21
相关资源
最近更新 更多