iOS原生地图获取两点之间的距离
搜索iOS获取两点之间的距离,大多数是类似以下的答案:
//第一个坐标
CLLocation *current=[[CLLocation alloc] initWithLatitude:32.178722 longitude:119.508619];
//第二个坐标
CLLocation *before=[[CLLocation alloc] initWithLatitude:32.206340 longitude:119.425600];
// 计算距离
CLLocationDistance meters=[current distanceFromLocation:before];
以上方法是用来获取两点之间的直线距离,要获取两点之间真正路线规划的距离,还需要借助苹果提供的其他类:
1、首先要对经纬度进行包装,包装成节点信息:CLLocationCoordinate2D->MKPlacemark->MKMapItem;
2、其次创建路线请求(设置参数,发送请求),通过calculateDirectionsWithCompletionHandler获得路线数组信息;
3、再根据获取的路线数组信息进行计算,得出每个路线的距离,并根据需求取出你想要的数据;
以下代码是根据两点获取最小路线距离;
//起点和终点的经纬度
CLLocationCoordinate2D start = {39.908760,116.397578};
CLLocationCoordinate2D end = {40.908760,117.397578};
//起点终点的详细信息
MKPlacemark *startPlace = [[MKPlacemark alloc]initWithCoordinate:start addressDictionary:nil];
MKPlacemark *endPlace = [[MKPlacemark alloc]initWithCoordinate:end addressDictionary:nil];
//起点 终点的 节点
MKMapItem *startItem = [[MKMapItem alloc]initWithPlacemark:startPlace];
MKMapItem *endItem = [[MKMapItem alloc]initWithPlacemark:endPlace];
//路线请求
MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
request.source= startItem;
request.destination= endItem;
//发送请求
MKDirections *directions = [[MKDirections alloc]initWithRequest:request];
__blockNSIntegersumDistance =0;
//计算
[directionscalculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
if(!error) {
NSIntegerminDistance =0;
for(inti =0; i < response.routes.count; i++) {
sumDistance =0;
//取出一条路线
MKRoute*route = response.routes[i];
//关键节点
for(MKRouteStep*stepinroute.steps){
//距离
sumDistance += step.distance;
}
//下标为0或者新计算出来的数据小于保存的最小数据,给最小数据重新赋值
if(i ==0|| minDistance > sumDistance) {
minDistance = sumDistance;
}
NSLog(@"总距离 %ld",minDistance);
}
}
}];