如何计算目标c中的两个坐标距离? [英] how to calculate two coordinates distance in objective c?

查看:113
本文介绍了如何计算目标c中的两个坐标距离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为标题如何?我已经尝试了谷歌地球的代码,但似乎结果与谷歌地图计算结果不同。 (double)GetDistance:(double)lat1 long1:(double)lng1 la2:(double)下面提供了我所做的代码: )lat2 long2:(double)lng2 {
// NSLog(@latitude 1:%。7f,longitude1:%。7f,latitude2:%。7f,longitude2:%。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
但是当我使用谷歌地图获取两个相同坐标之间的方向时,它显示我的距离大约是8公里

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

解决方案

iPhone,为什么不使用内置的距离函数而不是滚动自己的? location1和location2是CLLocation对象。

  CLLocationDistance distance = [location1 getDistanceFrom:location2]; 


as title how to? i have tried the code from google earth, but seem like the result is different with the google map calculation result. below provided the code i did

-(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;
}

the EARTH_RADIUS value is 6378.138

by using this function by provided two coordinates the result come out is 4.5kM but when i use google map get direction between two same coordinates, it show me the distance is about 8km

can anyone help to point out the problem of my code?

解决方案

Since this is tagged iPhone, why not use the built-in distance function rather than rolling your own? location1 and location2 are CLLocation objects.

CLLocationDistance distance = [location1 getDistanceFrom:location2];

这篇关于如何计算目标c中的两个坐标距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆