iOS:两个位置之间的路线距离(路线,而不是直线)

时间:2012-11-27 17:00:53

标签: ios dictionary mkmapview google-direction

我有一个带有多个注释的MKMapview。当用户选择注释时,“标注”视图显示位置的名称以及位置和用户位置之间的距离。

我被困在了远方。在iOS 5之前,我可以使用Google方向API来获取距离,但现在我不能。有没有替代方案?

谢谢!

编辑:

我所指的距离是两个地点之间的路线距离。这条路线有很多路线。由于“distanceFromLocation:”

,它不是直线的距离

2 个答案:

答案 0 :(得分:4)

如果您有两个CLLocations,则可以使用distanceFromLocation:方法获取它们之间的距离。

示例:

CLLocation* first = [[CLLocation alloc] initWithLatitude:firstLatitude longitude:firstLongitude];
CLLocation* second = [[CLLocation alloc] initWithLatitude:secondLatitude longitude:secondLongitude];

CGFloat distance = [first distanceFromLocation:second];

您可以从注释类的coordinate或类似属性中获取注释的纬度和经度(而不是注释视图)。

如果您有注释列表并希望获得它们之间路径的距离,只需:

CGFloat distance = 0;
for(int idx = 0; idx < [mapView.annotations count] - 1; ++idx) {
    CLLocationCoordinate2D firstCoord = [mapView.annotations[idx] coordinate];
    CLLocationCoordinate2D secondCoord = [mapView.annotations[idx + 1] coordinate];

    CLLocation* first = [[CLLocation alloc] initWithLatitude:firstCoord.latitude longitude:secondCoord.latitude];
    CLLocation* second = [[CLLocation alloc] initWithLatitude:secondCoord.latitude longitude:secondCoord.longitude];

    distance += [first distanceFromLocation:second];
}

答案 1 :(得分:2)

现在(iOS 7及更高版本)您可以获得包含MKDirections,MKDirectionsRequest和MKDirectionsResponse的路线。

路线信息是MKRoute(有距离属性)。

例如follow this link

相关问题