gpt4 book ai didi

ios - 从 MKMapView 中绘制的路线测量距离(以米为单位)

转载 作者:行者123 更新时间:2023-11-28 17:59:38 25 4
gpt4 key购买 nike

如何计算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

关于ios - 从 MKMapView 中绘制的路线测量距离(以米为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23572229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com