需要从存储的坐标到当前位置的距离

时间:2012-11-21 06:07:55

标签: core-location cllocation mkmapview

我试图将我存储到核心数据中的经度和纬度与当前位置保持一定距离。我有这个代码,但我无法弄清楚如何集成代码使用我存储在核心数据中的坐标。如何使用存储在核心数据中的坐标来获取用户位置的距离?谢谢你的帮助!

CLLocation *to = [[CLLocation alloc]
                  initWithLatitude:mapView.userLocation.coordinate.latitude
                  longitude:mapView.userLocation.coordinate.longitude];

CLLocation *from = [[CLLocation alloc]
                    initWithLatitude:mapView.userLocation.coordinate.latitude
                    longitude:mapView.userLocation.coordinate.longitude];

CLLocationDistance distance = [to distanceFromLocation:from];

_distance.text = [[NSString alloc]initWithFormat:@"%g",distance];

我得到了这样的核心数据坐标:

_buyLong.text = [[_itemDetailArray valueForKey:@"longitude"] description];
_buyLatitude.text = [[_itemDetailArray valueForKey:@"latitude"] description];

1 个答案:

答案 0 :(得分:1)

想出来,希望有人可以受益:

NSString *savedLatitude = [[_itemDetailArray valueForKey:@"latitude"] description];
    double latDouble = [savedLatitude doubleValue];

NSString *savedLongitude = [[_itemDetailArray valueForKey:@"longitude"] description];
    double longDouble = [savedLongitude doubleValue];

NSLog(@"Value Lat: %f", latDouble);
NSLog(@"Value Long: %f", longDouble);

// Item Location from Array
itemCoordinate.latitude = latDouble;
itemCoordinate.longitude = longDouble;

// User Location from Device
[currentLocation stopUpdatingLocation];
theCoordinate.latitude = newLocation.coordinate.latitude;
theCoordinate.longitude = newLocation.coordinate.longitude;

CLLocation *loc = [[CLLocation alloc] initWithLatitude:theCoordinate.latitude longitude:theCoordinate.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:itemCoordinate.latitude longitude:itemCoordinate.longitude];

CLLocationDistance dist = [loc distanceFromLocation:loc2] *0.0006213; // Convert Meters to Miles
NSString *distance = [NSString stringWithFormat:@"%.1f",dist];

NSLog(@"DIST in Miles: %f", dist); // Wrong formatting may show wrong value!}

_distance.text = distance;