如何计算目标c中的两个坐标距离?

时间:2009-12-30 15:58:52

标签: iphone google-maps

作为标题如何?我已经尝试了谷歌地球的代码,但似乎结果与谷歌地图计算结果不同。下面提供了我做的代码

-(double)GetDistance:(double)lat1 long1:(double)lng1 la2:(double)lat2 long2:(double)lng2 {
    //NSLog(@"latitude 1:%.7f,longitude1:%.7f,latitude2:%.7f,longtitude2:%.7f",lat1,lng1,lat2,lng2);
    double radLat1 = [self rad:lat1];
    double radLat2 = [self rad:lat2];
    double a = radLat1 - radLat2;
    double b = [self rad:lng1] -[self rad:lng2];
    double s = 2 * asin(sqrt(pow(sin(a/2),2) + cos(radLat1)*cos(radLat2)*pow(sin(b/2),2)));
    s = s * EARTH_RADIUS;
    s = round(s * 10000) / 10000;
    return s;
}

-(double)rad:(double)d
{
    return d *3.14159265 / 180.0;
}

EARTH_RADIUS值为6378.138

通过使用此函数提供两个坐标,结果出来是4.5kM 但是当我使用谷歌地图获取两个相同坐标之间的方向时,它显示我的距离约为8km

任何人都可以帮助指出我的代码问题吗?

5 个答案:

答案 0 :(得分:50)

由于这是标记iPhone,为什么不使用内置的距离功能而不是自己滚动? location1和location2是CLLocation对象。

CLLocationDistance distance = [location1 getDistanceFrom:location2];

答案 1 :(得分:15)

这是一个简单的代码(假设你只有两点的纬度和经度)

CLLocation *startLocation = [[CLLocation alloc] initWithLatitude:startLatitude longitude:startLongitude];
CLLocation *endLocation = [[CLLocation alloc] initWithLatitude:endLatitude longitude:endLongitude];
CLLocationDistance distance = [startLocation distanceFromLocation:endLocation]; // aka double

不要忘记将MapKit Framework添加到您的项目中,并在您的文件中导入MapKit:

#import <MapKit/MapKit.h>

答案 2 :(得分:5)

Google地图可能会为您提供行驶距离,而您列出的大圆方程式将是直线表面距离。如果直接从A点到B点存在直线曲面道路,Google地图可能会给您与您在那里的等式相同的距离。

答案 3 :(得分:1)

根据您的应用需求,您应该可以直接使用google API计算大圆距离或行驶距离。

请参阅GLatLong::distanceFromGDirections::getDistance

答案 4 :(得分:1)

getDistanceFrom:

isDeprecated 尝试使用

[newLocation distanceFromLocation:oldLocation

相关问题