我目前正在使用下面的代码,它将打开带有驾驶指南的地图到某个目的地.
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) } }))
现在打开地图时,您可以看到ETA和到目的地的总距离等信息.我如何提取或计算确切的信息?我只看到了客观c中的例子,但从未在swift中看到过.
你可以用它来做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!") } } }