2013-02-13 4 views
1

Я пробовал в течение нескольких дней и искал в Интернете, чтобы попытаться решить мою проблему, но я не могу найти соответствующую информацию.Получите расстояние от нескольких аннотаций

Я пытаюсь рассчитать расстояние от userLocation до моих аннотаций в UITableView с помощью CustomCell.

Я могу получить расчетные расстояния в NSLOG, но в моем таблицеView im получается 0.0km во всех моих ячейках.

Может ли кто-нибудь увидеть, что я делаю здесь неправильно?

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.mapView.delegate = self; 
    [self startLocationServices]; 

    NSString *path = [[NSBundle mainBundle] pathForResource:@"points" ofType:@"plist"]; 
    NSArray *anns = [NSArray arrayWithContentsOfFile:path]; 

    for(NSMutableDictionary *note in anns) { 
     double doubleLatitude = [[note objectForKey:@"sculptureLatitudeKey"] doubleValue]; 
     double doubleLongitude = [[note objectForKey:@"sculptureLongitudeKey"] doubleValue]; 
     Annotation* myAnnotation = [[Annotation alloc] init]; 
     CLLocationCoordinate2D theCoordinate; 
     theCoordinate.latitude = doubleLatitude; 
     theCoordinate.longitude = doubleLongitude; 
     myAnnotation.coordinate = theCoordinate; 
     myAnnotation.title = [note objectForKey:@"sculptureNameKey"]; 
     myAnnotation.subtitle = [note objectForKey:@"sculptureAddressKey"]; 
     myAnnotation.sculptureIdKey = [note objectForKey:@"sculptureIdKey"]; 
     [self.mapView addAnnotation:myAnnotation]; 
    } 
} 

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation 
{ 
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 5000, 5000); 
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES]; 
} 

- (void)startLocationServices 
{ 
    if (self.locationManager == nil) 
    { 
     self.locationManager = [CLLocationManager new]; 
    } 
    [self.locationManager setDelegate:self]; 
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; 
    [self.locationManager setDistanceFilter:kCLDistanceFilterNone]; 

    [self.locationManager startUpdatingLocation]; 
} 

- (void)stopLocationServices 
{ 
    [self.locationManager stopUpdatingLocation]; 
    [self.locationManager setDelegate:nil]; 
} 


- (void)locationManager:(CLLocationManager *)manager 
    didUpdateToLocation:(CLLocation *)newLocation 
      fromLocation:(CLLocation *)oldLocation 
{  
    for (Annotation *annotation in self.mapView.annotations) 
    { 
     CLLocationCoordinate2D coord = [annotation coordinate]; 
     CLLocation *annLocation = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude]; 

     CLLocationDistance calculatedDistance = [annLocation distanceFromLocation:newLocation]; 
     NSLog(@"Nice distance:%.1f m\n", calculatedDistance); 
    } 
} 

Мои NSLog показывает, что это, и я только 3 аннотаций в моем .plist

2013-02-13 16:46:14.736 TalkingSculpture[91833:c07] Nice distance:762.1 m 
2013-02-13 16:46:14.736 TalkingSculpture[91833:c07] Nice distance:98.8 m 
2013-02-13 16:46:14.736 TalkingSculpture[91833:c07] Nice distance:2704.3 m 
2013-02-13 16:46:14.737 TalkingSculpture[91833:c07] Nice distance:0.0 m 

Мой customCell.h

#import <UIKit/UIKit.h> 

@interface customCell : UITableViewCell 

@property (weak, nonatomic) IBOutlet UILabel *customTitle; 
@property (weak, nonatomic) IBOutlet UILabel *customSubTitle; 
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel; 

@end 

И customCell.m

#import "customCell.h" 

@implementation customCell 

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     // Initialization code 
    } 
    return self; 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated 
{ 
    [super setSelected:selected animated:animated]; 

    // Configure the view for the selected state 
} 

@end 

в представлении таблицы я заполняю cellFor RowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{  
    static NSString *CellIdentifier = @"Cell"; 
    customCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 
    if (!cell) 
    { 
     cell = [[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    cell.customTitle.text = [[self.locationsArray objectAtIndex:indexPath.row] valueForKey:@"sculptureNameKey"]; 
    cell.customSubTitle.text = [[self.locationsArray objectAtIndex:indexPath.row] valueForKey:@"sculptureAddressKey"]; 
    cell.distanceLabel.text = [NSString stringWithFormat:@"%.1f km\n", _calulatedDistance]; 

    return cell; 
} 
+0

Можете ли вы показать код, задающий расстояние в пользовательской ячейке? – Anna

+0

Правильно ли вы форматируете текст в ячейке? Например,% .1f? – Ondrej

+0

@AnnaKarenina Я только что обновил свой вопрос с большим количеством кода от customCell и cellForRowAtIndexPath – hpetersen

ответ

0

Не знаю, нужен ли вам еще ответ на этот вопрос. Но каждый раз, когда отображается табличное представление, вам нужно будет заполнить массив (или альтернативу) для хранения всех текущих расстояний. Затем в cellForRowAtIndexPath установите метку на соответствующие расстояния от этого массива. То, что вы делаете в этом коде, это установить его на ivar, который либо равен нулю, либо 0, когда вы его вызываете.

Смежные вопросы