首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CLLocation distanceFromLocation

CLLocation distanceFromLocation
EN

Stack Overflow用户
提问于 2011-03-05 04:36:56
回答 2查看 18.5K关注 0票数 4

我正在使用CLLocation计算与当前用户位置的距离,并添加一个注释。然而,我只是想知道这是否正确。我目前使用的是iPhone模拟器,根据MKMapView的说法,iPhone模拟器位于以下位置:

代码语言:javascript
复制
Lat: 0 Long: -1067024384

注释的位置是:

代码语言:javascript
复制
workingCoordinate.latitude = 40.763856;
workingCoordinate.longitude = -73.973034;

然而,如果你在谷歌地图上看一看,你会发现这些距离有多近,但根据CLLocation的说法,它们却相距甚远。我使用下面的代码来确定它们之间的距离。

代码语言:javascript
复制
CLLocation *loc = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];
CLLocationDistance dist = [loc distanceFromLocation:loc2];
int distance = dist
NSLog(@"%i", distance);

NSLogged的距离是12769908。我认为这是不正确的,因此我的代码一定有问题。

如果有,请您指点一下!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-03-05 08:22:19

你有两个坏习惯。

  1. 在需要硬件审查状态的情况下,您不应该依赖模拟器。尤其是当你想要正确的测试时。
  2. 你错误地处理了类型。所以你不能正确的检查值。经度-1067024384是怎样的?经度值是度。这意味着它的有效范围被经度的定义限制在-90.0到+90.0之间。

您的经度值超出范围。这意味着其中之一。您打印值错误或实际值错误。模拟器可能会打印错误值。或者你用错误的方法打印值。你必须尝试:

在具有真实硬件审查器的真实设备上进行

测试。

如果在此之后继续出现不好的结果,

对应用程序代码的所有进行复查。特别适用于打印、处理数值。检查>每种情况下是否使用了正确的类型和类型转换。因为你可能会习惯性地在某个地方做错误操作。

另外,我建议像这样检查所有的中间值。

代码语言:javascript
复制
CLLocationCoordinate2D annocoord = annotation.coordinate;
CLLocationCoordinate2D usercoord = self.mapView.userLocation.coordinate;

NSLog(@"ANNO  = %f, %f", annocoord.latitude, annocoord.longitude);
NSLog(@"USER = %f, %f", usercoord.latitude, usercoord.longitude);

CLLocation *loc = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];

NSLog(@"LOC  = %f, %f", loc.coordinate.latitude,  loc.coordinate.longitude);
NSLog(@"LOC2 = %f, %f", loc2.coordinate.latitude, loc2.coordinate.longitude);

CLLocationDistance dist = [loc distanceFromLocation:loc2];

NSLog(@"DIST: %f", dist); // Wrong formatting may show wrong value!
票数 9
EN

Stack Overflow用户

发布于 2011-03-05 04:42:34

尝试@"%f“,不要以这种方式转换它。

在CLLocation.h中

代码语言:javascript
复制
typedef double CLLocationDistance;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5198996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档