【问题标题】:Calculating distance between user & a nearby location, and calculated distance keeps showing up as 0?计算用户与附近位置之间的距离,计算出的距离一直显示为0?
【发布时间】:2013-05-08 00:04:57
【问题描述】:

我正在使用以下代码来计算我的应用用户位置与附近位置(注释)之间的距离。当我尝试在标签中将“距离”显示为文本时,它一直说计算的距离为 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];



    }

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

ViewController.m

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

任何帮助将不胜感激!

【问题讨论】:

    标签: uitableview mkmapview mkannotation xcode4.6


    【解决方案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;博士

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

    【讨论】:

    • 我取消了最后两行,并更改了我的变量名(哈哈)。请参阅上面的更新代码。那是我应该结束的吗?我不需要定义计算距离吗?谢谢你的帮助,顺便说一句!
    • 只要把它(距离)拉出显示代码中的注解,什么的。 (此外,单个变量 calculatedDistance 不足以保持多个距离(正如在 for 循环中要求的那样)。)
    • 好的,我现在完全明白为什么我的最后两行没用了,哈哈。你能用代码告诉我这看起来如何吗?我有点困惑!谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 2011-12-01
    • 2012-12-31
    • 2011-04-03
    • 2017-04-20
    • 2015-10-26
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    相关资源
    最近更新 更多