Using distanceFromLocation: on none CLLocation objects?
I have defined a class called FGLocation that conforms to the MKAnnotation protocol, what I am trying to do is measure the distance between two of these objects. I noticed that I could use the method dist开发者_如何学运维anceFromLocation: that is defined as a method for the CLLocation class. As you can see below I am creating two temp CLLocation objects to do the calculation, but I can't help thinking that I am maybe missing a better / easier way. Does anyone have any comments on what I am doing or how I might do it better?
// IS THERE A BETTER WAY TO DO THIS?
FGLocation *root = [annotations objectAtIndex:counter-1];
FGLocation *leaf = [annotations objectAtIndex:counter];
CLLocation *rootLocation = [[CLLocation alloc] initWithLatitude:[root coordinate].latitude longitude:[root coordinate].longitude];
CLLocation *leafLocation = [[CLLocation alloc] initWithLatitude:[leaf coordinate].latitude longitude:[leaf coordinate].longitude];
CLLocationDistance thisDistance = [rootLocation distanceFromLocation:leafLocation];
[rootLocation release];
[leafLocation release];
NB: my FGLocation object is defined as (see below) I noticed in the docs that I should not be subclassing CLLocation.
@interface FGLocation : NSObject <MKAnnotation> {
I think that what you are doing is a fair approach, with the possible exception that you might want to implement some sort of caching mechanism/threshold for recalculation if you are doing this often or on a lot of points. Calculating distances accurately involves non-Euclidean geometry and is computationally expensive. http://en.wikipedia.org/wiki/Haversine_formula
Depending on where the points are located on the globe and whether or not precision is highly important, you can also fudge things by pretending to be working in a Euclidean space and leveraging the Pythagorean theorem. I have used this kind of scheme to create a gross filter over a large dataset and then resorted to more precise calculations on points that pass the filter.
精彩评论