在MKMapView中以米为单位测量绘制路线的距离[英] Measuring distance in meters from a drawn route in MKMapView

本文是小编为大家收集整理的关于在MKMapView中以米为单位测量绘制路线的距离的处理方法,想解了在MKMapView中以米为单位测量绘制路线的距离的问题怎么解决?在MKMapView中以米为单位测量绘制路线的距离问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

如何计算 MKMapView 中两个坐标之间的路线距离?我问的不是直线距离,而是转弯路线的距离.

推荐答案

我假设您正在使用 MKDirectionsRequest 来获取 MKDirectionsResponse 从中获取路线.例如:

MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];

// source and destination are the relevant MKMapItem's
request.source = source;
request.destination = destination;

// Specify the transportation type
request.transportType = MKDirectionsTransportTypeAutomobile;

// If you're open to getting more than one route, requestsAlternateRoutes = YES; else requestsAlternateRoutes = NO;
request.requestsAlternateRoutes = YES;

MKDirections *directions = [[MKDirections alloc] initWithRequest:request];

[directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {

    if (!error) {
        self.directionsResponse = response;                           
    }
}];

一旦您获得 MKDirectionsResponse(在本例中为 self.directionsResponse)并根据该响应确定特定的路线索引,则可以使用以下方法找到该路线的 CLLocationDistance(以米为单位):

MKRoute *route = self.directionsResponse.routes[currentRoute];
CLLocationDistance distance = route.distance;

如果您不知道要使用哪条特定路线——例如.如果您想根据距离决定路线 - 您可以通过 directionsResponse.route 数组循环获取所有路线距离.

编辑:此外,如果您想及时找到距离(以秒为单位),您可以使用:

NSTimeInterval seconds = route.expectedTravelTime;
<小时>

在 Swift 中:

let request:MKDirectionsRequest = MKDirectionsRequest()

// source and destination are the relevant MKMapItems
request.setSource(source)
request.setDestination(destination)

// Specify the transportation type
request.transportType = MKDirectionsTransportType.Automobile;

// If you're open to getting more than one route, 
// requestsAlternateRoutes = true; else requestsAlternateRoutes = false;
request.requestsAlternateRoutes = true

let directions = MKDirections(request: request)

directions.calculateDirectionsWithCompletionHandler ({
    (response: MKDirectionsResponse?, error: NSError?) in

    if error == nil {
        self.directionsResponse = response
    }
})

获取距离:

let route = directionsResponse.routes[currentRoute] as MKRoute
let distance = route.distance

要获得预期的旅行时间:

let seconds = route.expectedTravelTime

本文地址:https://www.itbaoku.cn/post/924648.html