我想用Haversine公式计算两个地方之间的距离。实际上我有两个地方的纬度和经度值。现在我想用Haversine公式计算那些地方之间的距离。
例如:
First Place:
"lat" : 12.97159870,
"lng" : -77.59456270
Second Place:
"lat" : 9.915996999999999,
"lng" : -78.1218470
},
现在我想用 Haversine Formula 来计算距离。
请帮帮我。 谢谢!
答案 0 :(得分:12)
您可以使用CLLocation类(CoreLocation.framework)方法的distanceFromLocation:(CLLocation *)loc;
CLLocation *locA = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2];
CLLocationDistance distance = [locA distanceFromLocation:locB];
[locA release]; [locB release];
答案 1 :(得分:6)
iOS提供了计算两个地理位置之间距离的标准方法 - 您需要使用CLLocation类:
#import <CoreLocation/CoreLocation.h>
CLLocation *loc1 = [[[CLLocation alloc] initWithLatitude:12.97159870 longitude:-77.59456270] autorelease];
CLLocation *loc2 = [[[CLLocation alloc] initWithLatitude: 9.915996 longitude:-78.1218470] autorelease];
double distance = [loc1 distanceFromLocation: loc2];
您还需要添加CoreLocation.framework
以链接您的项目。
答案 2 :(得分:1)
//将库复制到项目https://github.com/heycarsten/haversine-objc。然后使用
获得两个位置之间的距离 Haversine *hvs = [[Haversine alloc]initWithLat1:Lati1 lon1:Longi1 lat2:Lati2 lon2:Longi2];
//使用数学公式获取距离..
double dLat1InRad = DEGREES_TO_RADIANS(Lati1);
double dLong1InRad = DEGREES_TO_RADIANS(Longi1);
double dLat2InRad = DEGREES_TO_RADIANS(Lati2);
double dLong2InRad = DEGREES_TO_RADIANS(Longi2);
double dLongitude = dLong2InRad - dLong1InRad;
double dLatitude = dLat2InRad - dLat1InRad;
double a = pow(sin(dLatitude/2.0), 2)+ cos(dLat1InRad) * cos(dLat2InRad) * pow(sin(dLongitude / 2.0), 2);
double c = 2.0 * asin(sqrt(a));
const double kEarthRadiusKms = 6376.5;
double dDistance = kEarthRadiusKms * c;