iPhone与当前位置的距离为副标题

时间:2012-10-02 02:33:49

标签: iphone objective-c xcode ipad

我试图找到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。我做错了什么?

修改

所以我现在正确计算当前位置的距离。但是如何将其设置为将其设置为引脚的副标题?

以下是我找到距离的方法:

- (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];
    }
}

1 个答案:

答案 0 :(得分:0)

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

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

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

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