根据道路计算两个位置之间的距离



我有两个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;

但我不确定我得到的值是正确的。
这些值air距离吗?
是否可以根据道路获得距离?
我需要用户与汽车必须经过的距离

这些值为空中距离。

你不能用Apple SDK找到基于道路的距离。尝试直接询问google api http://code.google.com/intl/fr-FR/apis/maps/index.html

使用CLLocation代替CLLocationCoordinate:-

CLLocation有一个名为

的init方法
-(id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude. 

然后使用

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

获取Road上两个CLLocation对象之间的距离。

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

@coolanilkothari所说的几乎是正确的,除了getDistanceFrom在ios 3.2中被弃用。这是苹果的文档必须说的…

getDistanceFrom:

返回从接收者位置到目标的距离(以米为单位)指定的位置。(已在iOS 3.2中弃用。使用方法代替distanceFromLocation。)- (CLLocationDistance)getDistanceFrom:(const CLLocation *)location Parameters

位置
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;
}

你只需要传递原点和目的地坐标,然后解析结果

http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Vancouver + BC&目的地=圣+ Francisco&传感器= false

相关内容

最新更新