簡體   English   中英

根據道路計算兩個位置之間的距離

[英]Calculate distance between two location based on roads

我有兩個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;

但是我不確定我得到的價值觀是否正確。
這些值是空中距離嗎?
是否可以根據道路獲得距離?
我需要用戶必須通過汽車的距離。

這些值是空中距離。

使用Apple SDK無法找到基於道路的距離。 嘗試直接詢問Google API http://code.google.com/intl/fr-FR/apis/maps/index.html

使用CLLocation而不是CLLocationCoordinate:-

CLLocation有一個名為的初始化方法

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

然后使用

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

獲取Road上兩個CLLocation對象之間的距離。

您將獲得的距離以公里為單位。

從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;

}

@coolanilkothari所說的幾乎是正確的,除了在iOS 3.2中不贊成使用getDistanceFrom。 這就是蘋果文檔必須說的。

getDistanceFrom:

返回從接收器位置到指定位置的距離(以米為單位)。 (在iOS 3.2中已棄用。請改用distanceFromLocation:方法。)-(CLLocationDistance)getDistanceFrom:(const CLLocation *)location參數

位置

 The other location. 

返回值

兩個位置之間的距離(以米為單位)。 討論區

該方法通過跟蹤兩個位置之間遵循地球曲率的直線來測量兩個位置之間的距離。 產生的弧線是平滑的曲線,並且沒有考慮兩個位置之間的特定高度變化。 可用性

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

在CLLocation.h中聲明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM