0

我正在使用以下代码来计算我的应用用户位置与附近位置(注释)之间的距离。当我尝试在标签中将“距离”显示为文本时,它一直说计算的距离为 0。这是为什么呢?

*请注意,我的表格使用放置在 MapView 上的坐标来确定距离。

这是我用来计算从我的用户到附近位置的距离的代码

MapViewController.m

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

   for (MapViewAnnotation *annotation in self.mapView.annotations) {
CLLocationCoordinate2D coord = [annotation coordinate];
CLLocation *annotationLocation = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude];
annotation.distance = [newLocation distanceFromLocation:annotationLocation];



    }

这是我用来在标签中显示计算距离的位(位于我的自定义单元格中以显示在表格视图中):

视图控制器.m

cell.distanceLabel.text = [NSString stringWithFormat:@"%f m.", calculatedDistance];

任何帮助将非常感激!

4

1 回答 1

1
for (MapViewAnnotation *annotation in self.mapView.annotations) {
  CLLocationCoordinate2D coord = [annotation coordinate];
  CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude];

那不是用户的位置,而是注释的位置。但除了奇怪的变量名:

CLLocationDistance calculatedDistance = [userLocation distanceFromLocation:userLocation];

从一个位置到它自己的距离是 0。那条线可能是一个错误。也许你的意思是

CLLocationDistance calculatedDistance = [newLocation distanceFromLocation:userLocation];

这将返回用户的新位置和(错误命名的)注释位置之间的距离——可能是你想要的。当然,你实际上只是在距离到自我计算上面的那一行计算,然后在两行之后把它扔掉。

tl;博士

扔掉最后两行,它们没用。

于 2013-05-08T00:21:09.677 回答