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

4 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;
}
Run Code Online (Sandbox Code Playgroud)

EARTH_RADIUS值为6378.138

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

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

Jan*_*les 50

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

CLLocationDistance distance = [location1 getDistanceFrom:location2];
Run Code Online (Sandbox Code Playgroud)

  • 在iOS 7.1中,不推荐使用`[location1 getDistanceFrom:location2]`.我正在使用`[location1 distanceFromLocation:location2]`. (10认同)
  • 对于任何早于iOS 3.2的东西:[location1 distanceFromLocation:location2] (2认同)

dul*_*gan 15

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

CLLocation *startLocation = [[CLLocation alloc] initWithLatitude:startLatitude longitude:startLongitude];
CLLocation *endLocation = [[CLLocation alloc] initWithLatitude:endLatitude longitude:endLongitude];
CLLocationDistance distance = [startLocation distanceFromLocation:endLocation]; // aka double
Run Code Online (Sandbox Code Playgroud)

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

#import <MapKit/MapKit.h>
Run Code Online (Sandbox Code Playgroud)


Nic*_*sen 5

谷歌地图很可能会给你驱动距离,而你列出的大圆方程将是直线表面距离.如果直接从A点到B点存在直线曲面道路,Google地图可能会给您与您在那里的等式相同的距离.