使用CLLocation计算距离iOS MapKit

时间:2011-07-13 20:55:57

标签: ios mapkit

我试图用纬度和经度找到以英里为单位的距离。我有以下方法:

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    if(!newLocation) return; 

    if ((oldLocation.coordinate.latitude != newLocation.coordinate.latitude) &&
        (oldLocation.coordinate.longitude != newLocation.coordinate.longitude))
    {



        CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:oldLocation.coordinate.latitude longitude:oldLocation.coordinate.longitude];
        CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.latitude];

        CLLocationDistance distance = ([loc2 distanceFromLocation:loc1]) * 0.000621371192;

        //distance = distance; 

        NSLog(@"Total Distance %f in miles",distance);
    }

}

出于某种原因,它打印出类似5678.32英里的东西。这个位置非常固定,根本不动。

2 个答案:

答案 0 :(得分:5)

CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.(!!!!!)latitude longitude:newLocation.coordinate.(!!!!!)latitude];

答案 1 :(得分:3)

您正在使用经度和纬度的新位置的纬度初始化loc2:

这一行:

CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.latitude];

应该说:

CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];

希望它有所帮助!