2011-12-08 116 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; 

} 
相關問題