快速计算地图的距离和预计到达时间
Posted
技术标签:
【中文标题】快速计算地图的距离和预计到达时间【英文标题】:Calculate distance and ETA from maps in swift 【发布时间】:2015-12-24 15:51:20 【问题描述】:我目前正在使用下面的代码打开带有前往某个目的地的驾驶指南的地图。
let lat1 : NSString = "57.619302"
let lng1 : NSString = "11.954928"
let latitute:CLLocationDegrees = lat1.doubleValue
let longitute:CLLocationDegrees = lng1.doubleValue
let regionDistance:CLLocationDistance = 10000
let coordinates = CLLocationCoordinate2DMake(latitute, longitute)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
let options = [
MKLaunchOptionsMapCenterKey: NSValue(MKCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(MKCoordinateSpan: regionSpan.span),
MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving
]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = "Timo's Crib"
dispatch_async(dispatch_get_main_queue())
mapItem.openInMapsWithLaunchOptions(options)
))
现在打开地图时,您可以看到诸如预计到达时间和到目的地的总距离等信息。我如何提取或计算准确的信息?我只在目标 c 中看到过示例,但从未在 swift 中看到过。
【问题讨论】:
【参考方案1】:您可以使用MKDirectionsRequest
来完成。首先我们需要我们当前的位置,因为从您的代码中我们看到您有目的地。我正在使用CLLocationManagerDelegate
方法locationManager(_:didUpdateLocations:)
。
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
let sourcePlacemark = MKPlacemark(coordinate: locations.last!.coordinate, addressDictionary: nil)
let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
..
完美。现在我们有了源项目和目标项目。现在只是请求(为了简单起见,我将您的代码放在方法中,但目标位置背后的逻辑可能应该从该方法中提取):
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
// Get current position
let sourcePlacemark = MKPlacemark(coordinate: locations.last!.coordinate, addressDictionary: nil)
let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
// Get destination position
let lat1: NSString = "57.619302"
let lng1: NSString = "11.954928"
let destinationCoordinates = CLLocationCoordinate2DMake(lat1.doubleValue, lng1.doubleValue)
let destinationPlacemark = MKPlacemark(coordinate: destinationCoordinates, addressDictionary: nil)
let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
// Create request
let request = MKDirectionsRequest()
request.source = sourceMapItem
request.destination = destinationMapItem
request.transportType = MKDirectionsTransportType.Automobile
request.requestsAlternateRoutes = false
let directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler response, error in
if let route = response?.routes.first
print("Distance: \(route.distance), ETA: \(route.expectedTravelTime)")
else
print("Error!")
【讨论】:
以上是关于快速计算地图的距离和预计到达时间的主要内容,如果未能解决你的问题,请参考以下文章