需要计算两个位置之间的距离

时间:2014-05-30 10:49:15

标签: ios

我试图计算两个位置之间的距离但是有些错误,因为每次距离都是0。

        float oldLatitude = [gInfo.latitude floatValue];
        float oldLongitude = [gInfo.longitude floatValue];
        CLLocation *oldLocation = [[CLLocation alloc] initWithLatitude:oldLatitude longitude:oldLongitude];
        CLLocation *newLocation = [[CLLocation alloc] initWithLatitude:newLatitude longitude:newLongitude];
        if (newLatitude == 0 && newLongitude == 0) {
            [self showAlarm2];
            return;
        }
        float distance = [newLocation distanceFromLocation:oldLocation];
        // distance 0 ????????
        int result = (int)roundf(distance );
        if (result < 0) {
            result = -result;
        }
       // long result = (long)distance;

        NSLog(gInfo.name );
        NSLog(@"Distance i meters: %i", result);
        //**************** filter group by check distance *************

       if (result <= 10) {
            [viewArray addObject:gInfo];
        }

1 个答案:

答案 0 :(得分:0)

使用此

 CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];

    CLLocation *location = [locationManager location];

    // Configure the new event with information from the location
    CLLocationCoordinate2D coordinate = [location coordinate];
    latitude = coordinate.latitude;
    longitude = coordinate.longitude;

    MKCoordinateRegion myRegion;
    MKCoordinateSpan mySpan;
    mySpan.latitudeDelta = 1.0f;
    mySpan.longitudeDelta = 1.0f;
    myRegion.center = coordinate;
    myRegion.span = mySpan;




  //-----------------------------------------------
        NSDictionary *dict = (NSDictionary*)[arrayJsonData objectAtIndex:indexPath.row];
        CLLocation *locA = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
        CLLocation *locB = [[CLLocation alloc] initWithLatitude:[[dict1 valueForKey:@"Latitude"] doubleValue] longitude:[[dict1 valueForKey:@"Longitude"] doubleValue]];

        CLLocationDistance distance = [locA distanceFromLocation:locB];

        double distanceInMiles = (distance/CONVERSION_TO_MILES); 
// CONVERSION_TO_MILES 1609.344
相关问题