Search code examples
iphonedistancecllocationcllocationdistance

calculate distance between 2 coordinates iphone - best practice


I'm finishing an App in wish i need to show the user the distance between him and about 500 coordinates.

using the CLLocation method to calculate it, works well, but it takes about 1 minute in iPhone 4 to finish calculations for each location.

What is the best way to do it? Using span? Any other faster way?

Thanks all,

rui


Solution

  • I think Sahgal is right, here is some code, perhaps it will help you.

    +(CGFloat)calculateDistanceBetweenSource:(CLLocationCoordinate2D)firstCoords andDestination:(CLLocationCoordinate2D)secondCoords 
    {
    
        // this radius is in KM => if miles are needed it is calculated during setter of Place.distance
    
        double nRadius = 6371;
    
        // Get the difference between our two points
    
        // then convert the difference into radians
    
        double nDLat = (firstCoords.latitude - secondCoords.latitude)* (M_PI/180);
        double nDLon = (firstCoords.longitude - secondCoords.longitude)* (M_PI/180);
    
        double nLat1 =  secondCoords.latitude * (M_PI/180);
        double nLat2 =  secondCoords.latitude * (M_PI/180);
    
        double nA = pow ( sin(nDLat/2), 2 ) + cos(nLat1) * cos(nLat2) * pow ( sin(nDLon/2), 2 );
    
        double nC = 2 * atan2( sqrt(nA), sqrt( 1 - nA ));
    
        double nD = nRadius * nC;
    
        NSLog(@"Distance is %f",nD);
    
        return nD; // converts to miles or not (if en_) => implicit in method
    }