首先,我想说我对Swift很新。在我的情况下,最简单的答案可能是最好的。
我目前有一些代码使用mapkit绘制从当前位置到大峡谷的路线。起始位置和结束位置是在代码中构建的:
let soucrceCoordinates = locationManager.location?.coordinate
//coordinates off the grand canyon, placeholder
let destCoordinates = CLLocationCoordinate2DMake(36.1070, -112.1130)
let sourcePlacemark = MKPlacemark(coordinate: soucrceCoordinates!)
let destPlacemark = MKPlacemark(coordinate: destCoordinates)
let sourceItem = MKMapItem(placemark: sourcePlacemark)
let destItem = MKMapItem(placemark: destPlacemark)
let directionRequest = MKDirectionsRequest()
directionRequest.source = sourceItem
directionRequest.destination = destItem
directionRequest.transportType = .automobile
现在我想计算这条路线的距离(而不是像乌鸦一样)。最好的单位是米。反正有没有这样做?提前致谢
答案 0 :(得分:1)
您还必须创建MKDirections
个实例,而不仅仅是MKDirectionsRequest
并调用MKDirections.calculate
来计算导航路线。
let sourceCoordinates = locationManager.location?.coordinate
//coordinates of the grand canyon, placeholder
let destCoordinates = CLLocationCoordinate2D(latitude: 36.1070, longitude: -112.1130)
let sourcePlacemark = MKPlacemark(coordinate: sourceCoordinates!)
let destPlacemark = MKPlacemark(coordinate: destCoordinates)
let sourceItem = MKMapItem(placemark: sourcePlacemark)
let destItem = MKMapItem(placemark: destPlacemark)
let directionRequest = MKDirectionsRequest()
directionRequest.source = sourceItem
directionRequest.destination = destItem
directionRequest.transportType = .automobile
let directions = MKDirections(request: directionRequest)
directions.calculate(completionHandler: { response, error in
guard error == nil, let response = response, let route = response.routes.first else {return}
print("Distance:\(route.distance)meters")
})