CLLocation distanceFromLocation

max*_*ax_ 4 iphone xcode core-location mkmapview ios4

我正在使用CLLocation来计算当前用户位置和注释的距离.但是我只是想知道这是否正确.我目前正在使用iPhone模拟器,根据MKMapView,iPhone模拟器位于:

Lat: 0 Long: -1067024384
Run Code Online (Sandbox Code Playgroud)

注释的位置是:

workingCoordinate.latitude = 40.763856;
workingCoordinate.longitude = -73.973034;
Run Code Online (Sandbox Code Playgroud)

但是,如果你看看谷歌地图,你会发现这些距离有多近,但根据CLLocation这么远.我使用以下代码来确定它们之间的距离.

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

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

如果有,请你指出来!

Eon*_*nil 9

你有两个坏习惯.

  1. 在需要硬件审查状态的情况下,您不应该依赖模拟器.特别是当你想要正确的测试.
  2. 你错误地处理类型.因此您无法正确检查值.经度如何-1067024384?经度值是度.这意味着根据经度的定义,它的有效范围限制在-90.0~ + 90.0.

您的经度值超出范围.这意味着其中之一.您错误地打印了值或实际值是错误的.模拟器可以打印错误的值.或者您使用错误的方法打印了值.你得试试:

在具有真实硬件审查的真实设备上进行测试.

如果在那之后继续糟糕的结果,

查看所有应用程序代码.特别适用于印刷,处理价值.在每种情况下检查您是否使用了正确的类型和铸件.因为你可能习惯性地在某个地方做了越野车操作.

而且,我建议像这样检查所有中间值.

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!
Run Code Online (Sandbox Code Playgroud)