计算从一个位置到另一个位置的时间和距离
位置1:漕河泾,经纬度:(31.0930043380, 121.3221189118)
位置2:上海体育馆,经纬度:(31.1814714883, 121.4383290964)
1、生成各自的MapItem
MKPlacemark *sourcePlacemark = [[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake(31.0930043380, 121.3221189118) addressDictionary:nil];
MKMapItem *sourceItem = [[MKMapItem alloc] initWithPlacemark:sourcePlacemark];
sourceItem.name = @"漕河泾";
MKPlacemark *destinationPlacemark = [[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake(31.1814714883, 121.4383290964) addressDictionary:nil];
MKMapItem *destinationItem = [[MKMapItem alloc] initWithPlacemark:destinationPlacemark];
destinationItem.name = @"上海体育馆";
2、创建计算请求
MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
request.source = sourceItem;
request.destination = destinationItem;
request.transportType = MKDirectionsTransportTypeWalking;//步行模式
transportType有四种模式:
- MKDirectionsTransportTypeWalking;//步行模式
- MKDirectionsTransportTypeAutomobile//车行模式
- MKDirectionsTransportTypeTransit//公交模式
MKDirectionsRequest可以设置离开时间和到达时间,处理请求时会考虑这些因素,选择最合适的路径进行计算。
3、使用MKDirections对请求进行处理
MKDirections *walkingDirections = [[MKDirections alloc] initWithRequest:request];
[walkingDirections calculateETAWithCompletionHandler:^(MKETAResponse * _Nullable response, NSError * _Nullable error) {
}];
MKETAResponse有以下属性可以供我们使用:
- expectedTravelTime//持续的时长,单位:秒
- distance//距离,单位:米
- expectedDepartureDate//出发时间
- expectedArrivalDate//预计到达时间
2、在官方地图应用中展示两点间最佳路径及导航
[MKMapItem openMapsWithItems:@[sourceItem, destinationItem] launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeWalking}];
MKLaunchOptionsDirectionsModeKey有三种选择:
- MKLaunchOptionsDirectionsModeWalking//步行路线
- MKLaunchOptionsDirectionsModeDriving//车行路线
- MKLaunchOptionsDirectionsModeTransit//公交路线