歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> (iPhone/iPad開發)由經緯度計算距離

(iPhone/iPad開發)由經緯度計算距離

日期:2017/3/1 10:36:10   编辑:Linux編程

(iPhone/iPad開發)由經緯度計算距離,有2種計算方法

一種是寫一個算法自己手動計算

[cpp]

  1. #pragma mark - calculate distance
  2. +(double) LantitudeLongitudeDist:(double)lon1 other_Lat:(double)lat1 self_Lon:(double)lon2 self_Lat:(double)lat2{
  3. double er = 6378137; // 6378700.0f;
  4. //ave. radius = 6371.315 (someone said more accurate is 6366.707)
  5. //equatorial radius = 6378.388
  6. //nautical mile = 1.15078
  7. double radlat1 = PI*lat1/180.0f;
  8. double radlat2 = PI*lat2/180.0f;
  9. //now long.
  10. double radlong1 = PI*lon1/180.0f;
  11. double radlong2 = PI*lon2/180.0f;
  12. if( radlat1 < 0 ) radlat1 = PI/2 + fabs(radlat1);// south
  13. if( radlat1 > 0 ) radlat1 = PI/2 - fabs(radlat1);// north
  14. if( radlong1 < 0 ) radlong1 = PI*2 - fabs(radlong1);//west
  15. if( radlat2 < 0 ) radlat2 = PI/2 + fabs(radlat2);// south
  16. if( radlat2 > 0 ) radlat2 = PI/2 - fabs(radlat2);// north
  17. if( radlong2 < 0 ) radlong2 = PI*2 - fabs(radlong2);// west
  18. //spherical coordinates x=r*cos(ag)sin(at), y=r*sin(ag)*sin(at), z=r*cos(at)
  19. //zero ag is up so reverse lat
  20. double x1 = er * cos(radlong1) * sin(radlat1);
  21. double y1 = er * sin(radlong1) * sin(radlat1);
  22. double z1 = er * cos(radlat1);
  23. double x2 = er * cos(radlong2) * sin(radlat2);
  24. double y2 = er * sin(radlong2) * sin(radlat2);
  25. double z2 = er * cos(radlat2);
  26. double d = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
  27. //side, side, side, law of cosines and arccos
  28. double theta = acos((er*er+er*er-d*d)/(2*er*er));
  29. double dist = theta*er;
  30. return dist;
  31. }
另一種,蘋果公司sdk中已經封裝好了

distanceFromLocation方法

[cpp]

  1. CLLocation* orig=[[[CLLocation alloc] initWithLatitude:[mainDelegate.latitude_self doubleValue] longitude:[mainDelegate.longitude_self doubleValue]] autorelease];
  2. CLLocation* dist=[[[CLLocation alloc] initWithLatitude:[tmpNewsModel.latitude doubleValue] longitude:[tmpNewsModel.longitude doubleValue] ] autorelease];
  3. CLLocationDistance kilometers=[orig distanceFromLocation:dist]/1000;
  4. NSLog(@"____^^^^^^_____kilometers:%0.2f 公裡____________________",kilometers);
Copyright © Linux教程網 All Rights Reserved