Iphone 基于道路计算两个位置之间的距离
我有两个Iphone 基于道路计算两个位置之间的距离,iphone,objective-c,ios,mkmapview,core-location,Iphone,Objective C,Ios,Mkmapview,Core Location,我有两个MKCoordinateRegion对象。基于这些对象的值,我在地图上做了两个注释。 然后我计算这两个位置之间的距离: CLLocationCoordinate2D pointACoordinate = [ann coordinate]; CLLocation *pointALocation = [[CLLocation alloc] initWithLatitude:pointACoordinate.latitude longitude:pointACoordinate.lon
MKCoordinateRegion
对象。基于这些对象的值,我在地图上做了两个注释。
然后我计算这两个位置之间的距离:
CLLocationCoordinate2D pointACoordinate = [ann coordinate];
CLLocation *pointALocation = [[CLLocation alloc] initWithLatitude:pointACoordinate.latitude longitude:pointACoordinate.longitude];
CLLocationCoordinate2D pointBCoordinate = [ann2 coordinate];
CLLocation *pointBLocation = [[CLLocation alloc] initWithLatitude:pointBCoordinate.latitude longitude:pointBCoordinate.longitude];
float distanceMeters = [pointBLocation distanceFromLocation:pointALocation];
distanceMeters = distanceMeters / 1000;
但我不确定我得到的值是否正确
这些值是空中距离吗?
是否有可能根据道路获得距离呢?
我需要用户驾车经过的距离。这些值是空中距离
使用Apple SDK无法根据道路找到距离。尝试直接要求google API使用CLLocation而不是CLLocationCoordinate:-
CLLocation有一个名为
-(id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude.
然后使用
- (CLLocationDistance)getDistanceFrom:(const CLLocation *)location
获取道路上两个CLLocation对象之间的距离
您将得到的距离是公里。@colanilkothari所说的几乎是正确的,除了ios 3.2中不赞成getdistance。这就是苹果的医生们要说的
getDistanceFrom:
返回从接收器位置到目标位置的距离(以米为单位)
指定位置。(在iOS 3.2中已弃用。请使用
distanceFromLocation:改为方法。)
-(CLLocationDistance)getDistanceFrom:(const CLLocation*)位置参数
位置
The other location.
返回值
两个位置之间的距离(以米为单位)。讨论
该方法通过跟踪测量两个位置之间的距离
它们之间的一条直线,它沿着地球的曲率。这个
生成的圆弧是平滑曲线,不考虑
两个位置之间的具体高度变化。可用性
Available in iOS 2.0 and later.
Deprecated in iOS 3.2.
在CLLocation.h中声明
您只需传递原点和目标坐标,然后解析结果
自iOS7以来,您可以通过以下方式获得该信息:
+ (void)distanceByRoadFromPoint:(CLLocationCoordinate2D)fromPoint
toPoint:(CLLocationCoordinate2D)toPoint
completionHandler:(MKDirectionsHandler)completionHandler {
MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
request.transportType = MKDirectionsTransportTypeAutomobile;
request.source = [self mapItemFromCoordinate:fromPoint];
request.destination = [self mapItemFromCoordinate:toPoint];
MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
[directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * routeResponse, NSError *routeError) {
MKRoute *route = [routeResponse.routes firstObject];
CLLocationDistance distance = route.distance;
NSTimeInterval expectedTime = route.expectedTravelTime;
//call a completion handler that suits your situation
}];
}
+ (MKMapItem *)mapItemFromCoordinate:(CLLocationCoordinate2D)coordinate {
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil];
MKMapItem *item = [[MKMapItem alloc] initWithPlacemark:placemark];
return item;
}
但是我已经在我的代码中使用了CLLocation和distanceFromLocation:(是的,你无法通过道路获得精确的距离,因为api说“这种方法通过追踪两个位置之间的一条线来测量两个位置之间的距离,这条线沿着地球的曲率。”,你必须使用谷歌地图的方向api。距离是米而不是公里。