繁体   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