0

我正在尝试查找从 selectedAnnotation 到 userLocation 的距离。我在注释 NSObject 中添加了以下代码:

-(void) setDistanceFromCurrentLocation:(CLLocation *)currentLocation{

CLLocation *location2 = [[CLLocation alloc] initWithLatitude:self.latitude longitude:self.longitude];

[self setDistance:[currentLocation distanceFromLocation:location2]];
}

- (NSString *)subtitle
{
NSString *myDistance = [NSString stringWithFormat:@"%1.1f from current location", distance];
return myDistance;
}

现在在 didUpdatedidUpdateToLocation 我尝试使用来自这个问题的以下逻辑:https ://stackoverflow.com/a/10881683/984248

仍然返回 0.0。我究竟做错了什么?

编辑:

所以我现在正在正确计算与当前位置的距离。但是我如何传递它以将其设置为 pin 的字幕?

这是我找到距离的方法:

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

[self setCurrentLocation:newLocation];

// if not Current Location then update the currently displayed Dealer Annotation
for (int i=0; i<self.dataArray.count; i++){

    NSDictionary *dataDictionary = [self.dataArray objectAtIndex:i];
    NSArray *array = [dataDictionary objectForKey:@"Locations"];

    for (int i=0; i<array.count; i++){

        NSMutableDictionary *dictionary = [array objectAtIndex:i];

        CLLocation *pinLocation = [[CLLocation alloc] initWithLatitude:[[dictionary objectForKey:@"Latitude"] doubleValue] longitude:[[dictionary objectForKey:@"Longitude"] doubleValue]];

        [?????? setDistance:[self.currentLocation distanceFromLocation:pinLocation]];
    }
  }
}

这是我向地图添加图钉的方法:

for (int i=0; i<self.dataArray.count; i++){

    NSDictionary *dataDictionary = [self.dataArray objectAtIndex:i];
    NSArray *array = [dataDictionary objectForKey:@"Locations"];

    for (int i=0; i<array.count; i++){

        NSMutableDictionary *dictionary = [array objectAtIndex:i];

        MapAnnotation *annotation = [[MapAnnotation alloc] init];

        annotation.latitude = [[dictionary objectForKey:@"Latitude"] doubleValue];
        annotation.longitude = [[dictionary objectForKey:@"Longitude"] doubleValue];

        CLLocationCoordinate2D coord = {.latitude =
            annotation.latitude, .longitude =  annotation.longitude};
        MKCoordinateRegion region = {coord};

        annotation.title = [dictionary objectForKey:@"Name"];

        annotation.subtitle = ?????;
        annotation.coordinate = region.center;

        //Saving the dictionary of the pin to show contact info later
        annotation.sourceDictionary = dictionary;
        [mapView addAnnotation:annotation];
    }
}
4

1 回答 1

0

只是想知道,currentLocation 是否设置为 self.latitude,self.longitude?

在这种情况下,您将试图找到与自己的距离。尝试记录 currentLocation 参数以及 self.latitude 和 self.longitude 变量的纬度和经度值,并确保它们不同。

如果是,则尝试记录 [currentLocation distanceFromLocation:location2] 以查看它是否非零,如果是,那么您的 setDistance 方法就是问题所在。

除此之外,我能想到的只是您的距离变量在其他地方设置为 0,或者它是一个未使用 %1.1f 格式化的变量,因此格式化程序将其设置为 0.0

于 2012-10-02T04:59:19.217 回答