2011-12-08 57 views
0

我有两个MKCoordinateRegion对象。基于这些对象的值,我在地图上制作了两个annotations。 后来我计算这两个位置之间的距离:计算基于道路的两个位置之间的距离

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; 

但我是个不知道,我值获得是正确的。
这些值是否是距离?
基于道路可以得到距离吗?
我需要用户必须通过汽车的距离。

回答

2

@coolanilkothari说几乎是正确的,除了getDistanceFrom在ios 3.2中被弃用的事实。这就是苹果的文档有说..

getDistanceFrom:

返回到 指定位置从接收器的位置的距离(以米为单位)。 (弃用在IOS 3.2使用 distanceFromLocation:方法来代替。) - (CLLocationDistance)getDistanceFrom:(常量CLLocation *)位置参数

位置

The other location. 

返回值

的距离(以米计)在两个地点之间。讨论

该方法通过跟踪地球曲率之间的一条线来测量两个位置之间的距离。产生的弧线是平滑的曲线,并且不考虑两个位置之间的特定高度变化。可用性

Available in iOS 2.0 and later. 
Deprecated in iOS 3.2. 

宣布CLLocation.h

+0

但我已经在我的代码中使用CLLocation和distanceFromLocation:( – 1110

+0

yup,你不会通过道路得到确切的距离,因为api会说“这种方法通过跟踪曲线之间的一条直线来测量两个位置之间的距离的地球“,你将不得不使用谷歌地图方向api。 –

4

使用CLLocation代替CLLocationCoordinate: -

CLLocation有一个名为

-(id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude. 

然后使用

- (CLLocationDistance)getDistanceFrom:(const CLLocation *)location 

的init方法来获得之间的距离Road上的两个CLLocation对象。

您将得到的距离以公里为单位。

+3

距离是米未公里。 – progrmr

2

由于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; 

} 
相关问题