为什么MKMetersBetweenMapPoints和distanceFromLocation返回不同的值?

时间:2015-11-26 16:16:20

标签: mapkit core-location distance

我试图从我们的一个框架中删除MKMapKit的依赖项。我们仅使用MKMapKit来计算两个坐标之间的距离,使用函数MKMetersBetweenMapPoints

使用CLLocation对象和distanceFromLocation方法实现相同的代码,我会收到不同的结果。误差小于一米。

这是我正在运行的测试

- (double)distanceWithMapKitFrom:(CLLocationCoordinate2D)fromLocationCoordinate2D toCoordinate:(CLLocationCoordinate2D)toLocationCoordinate2D
{
    MKMapPoint mapPointFrom = MKMapPointForCoordinate(fromLocationCoordinate2D);
    MKMapPoint mapPointTo = MKMapPointForCoordinate(toLocationCoordinate2D);
    return MKMetersBetweenMapPoints(mapPointFrom, mapPointTo) / 1000;
}

- (double)distanceWithCoreLocationFrom:(CLLocationCoordinate2D)fromLocationCoordinate2D toCoordinate:(CLLocationCoordinate2D)toLocationCoordinate2D
{

    CLLocation *fromLocation = [[CLLocation alloc] initWithLatitude:fromLocationCoordinate2D.latitude longitude:fromLocationCoordinate2D.longitude];
    CLLocation *toLocation = [[CLLocation alloc] initWithLatitude:toLocationCoordinate2D.latitude longitude:toLocationCoordinate2D.longitude];

    return [fromLocation distanceFromLocation:toLocation] / 1000;
}

- (void)testDistanceWithoutMapKit
{
    for (int i = 0; i < 100; i++) {
        CLLocationCoordinate2D coord1 = RandomCoordinate2D();
        CLLocationCoordinate2D coord2 = RandomCoordinate2D();

        double distance1 = [self distanceWithMapKitFrom:coord1 toCoordinate:coord2];
        double distance2 = [self distanceWithCoreLocationFrom:coord1 toCoordinate:coord2];

        NSLog(@"%f %f %f", distance1, distance2, distance2 - distance1);

        XCTAssertEqual(distance1, distance2);
    }
}

RandomCoordinate2D功能可以找到here

0 个答案:

没有答案