我正在完成一个应用程序,希望我需要向用户显示他与大约500个坐标之间的距离。
使用CLLocation方法计算它,效果很好,但在iPhone 4中大约需要1分钟才能完成每个位置的计算。
最好的方法是什么?用span?还有其他更快的方法吗?
全心全意,
瑞
答案 0 :(得分:5)
我认为Sahgal是对的,这里有一些代码,也许它会帮助你。
+(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
}
答案 1 :(得分:2)
我已经看到了其他答案,不知道它们是否正确,但我认为有更好的解决方案:
- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location
你可以像这样使用它:
- (CLLocationDistance) DistanceBetweenCoordinate:(CLLocationCoordinate2D)originCoordinate andCoordinate:(CLLocationCoordinate2D)destinationCoordinate {
CLLocation *originLocation = [[CLLocation alloc] initWithLatitude:originCoordinate.latitude longitude:originCoordinate.longitude];
CLLocation *destinationLocation = [[CLLocation alloc] initWithLatitude:destinationCoordinate.latitude longitude:destinationCoordinate.longitude];
CLLocationDistance distance = [originLocation distanceFromLocation:destinationLocation];
[originLocation release];
[destinationLocation release];
return distance;
}
答案 2 :(得分:1)
这是代码..
-(NSString *)findDistanceBetweenTwoLatLon
{
int intEarthRadius = 3963;
double dblLat1 = DegreesToRadians(firstLatitude);
double dblLon1 = DegreesToRadians(firstLongitude);
double dblLat2 = DegreesToRadians(secondLatitude);
double dblLon2 = DegreesToRadians(secondLongitude);
float fltLat = dblLat2 - dblLat1;
float fltLon = dblLon2 - dblLon1;
double a = sin(fltLat/2) * sin(fltLat/2) + cos(dblLat2) * cos(dblLat2) * sin(fltLon/2) * sin(fltLon/2) ;
double c = 2 * atan2(sqrt(a), sqrt(1-a));
double d = intEarthRadius * c;
double dMeters = d * kOneMileMeters;
NSString *strDistance = [NSString stringWithFormat:@"%1.2f meters",dMeters];
return strDistance;
}
定义所有这个宏..
和度数到弧度
#define DegreesToRadians(degrees) (degrees * M_PI / 180)
其中M_PI
#define M_PI 3.14159265358979323846264338327950288
#define kOneMileMeters 1609.344
答案 3 :(得分:0)
你可以尝试另一种方法。你可以获取两个点的lat-long(假设lat-long发现不会花费那么多时间),并且有一些公式可以使用lat-long来计算距离。