как провести линию между x количеством движущихся аннотаций?

Привет, я новичок в xcode. Я разрабатываю приложение для iOS для отслеживания транспортных средств с использованием mkmap. Мне нужно рисовать линии между аннотациями каждые 5 секунд в зависимости от движения транспортного средства. Моя проблема заключается в том, что он рисует линию только в первый раз и со второго обновления интервал, это не сработает, мой код ниже,

- (void)viewDidLoad
{
   [super viewDidLoad];
   aTimer = [NSTimer scheduledTimerWithTimeInterval:5
                                                      target:self
                                                    selector:@selector(timerFired:)
                                                    userInfo:nil
                                                     repeats:YES];
}
-(void)timerFired:(NSTimer *) theTimer
{
    NSArray *existingpoints = MapViewC.annotations;
    if ([existingpoints count])
        [MapViewC removeAnnotations:existingpoints];
    NSString *urlMapString=[NSString stringWithFormat:@"http://www.logix.com/logix_webservice/map.php?format=json&truckno=%@",nam2];
    NSURL *urlMap=[NSURL URLWithString:urlMapString];
    NSData *dataMap=[NSData dataWithContentsOfURL:urlMap];
    NSError *errorMap;
    NSDictionary *jsonMap = [NSJSONSerialization JSONObjectWithData:dataMap options:kNilOptions error:&errorMap]; NSArray *resultsMap = [jsonMap valueForKey:@"posts"];
    NSArray *resMap = [resultsMap valueForKey:@"post"];
    NSArray *latitudeString=[resMap valueForKey:@"latitude"];
    NSString *latOrgstring = [latitudeString objectAtIndex:0];
    latitude=[latOrgstring doubleValue];
    NSArray *longitudeString=[resMap valueForKey:@"longitude"];
    NSString *longOrgstring = [longitudeString objectAtIndex:0];
    longitude=[longOrgstring doubleValue];
    NSString *ignation=[[resMap valueForKey:@"ignition"]objectAtIndex:0];
    //MAP VIEW Point
    MKCoordinateRegion myRegion;
    //Center
    CLLocationCoordinate2D center;
    center.latitude=latitude;
    center.longitude=longitude;
    //Span
    MKCoordinateSpan span;
    span.latitudeDelta=0.01f;
    span.longitudeDelta=0.01f;
    myRegion.center=center;
    myRegion.span=span;
    //Set our mapView
    [MapViewC setRegion:myRegion animated:YES];
    //Annotation
    //1.create coordinate for use with the annotation
    //CLLocationCoordinate2D wimbLocation;
    wimbLocation1.latitude=latitude;
    wimbLocation1.longitude=longitude;
    Annotation * myAnnotation= [Annotation alloc];
    CLLocation *someLocation=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:someLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        NSDictionary *dictionary = [[placemarks objectAtIndex:0] addressDictionary];
        addressOutlet=[dictionary valueForKey:@"Street"];
        City=[dictionary valueForKey:@"City"];
        State=[dictionary valueForKey:@"State"];
        myAnnotation.coordinate=wimbLocation1;
        if (addressOutlet!=NULL&&City!=NULL)
        {
            myAnnotation.title=addressOutlet;
            myAnnotation.subtitle=[NSString stringWithFormat:@"%@,%@", City, State];
        }
        [self.MapViewC addAnnotation:myAnnotation];
         [self line];
    }];
  }
  -(void)line
{
    CLLocationCoordinate2D coordinateArray[2];
    coordinateArray[0] = CLLocationCoordinate2DMake(latitude, longitude);
    coordinateArray[1] = CLLocationCoordinate2DMake(latitude, longitude);
    self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:2];
    [self.MapViewC addOverlay:self.routeLine];


}
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
    if(overlay == self.routeLine)
    {
        if(nil == self.routeLineView)
        {
            self.routeLineView = [[MKPolylineView alloc] initWithPolyline:self.routeLine];
            self.routeLineView.fillColor = [UIColor redColor];
            self.routeLineView.strokeColor = [UIColor redColor];
            self.routeLineView.lineWidth = 5;
        }
        return self.routeLineView;
    }
    return nil;
}

Пожалуйста, посоветуйте мне исправить мои ошибки. Заранее спасибо...


person iBeginner    schedule 21.07.2014    source источник
comment
Вопросы, требующие помощи в отладке (почему этот код не работает?), должны включать желаемое поведение, конкретную проблему или ошибку и кратчайший код, необходимый для их воспроизведения, в самом вопросе. Вопросы без четкой формулировки проблемы бесполезны для других читателей. См. раздел Как создать минимальный, полный и проверяемый пример.   -  person Neeku    schedule 21.07.2014
comment
вы просто комментируете эти строки if(overlay == self.routeLine) { if(nil == self.routeLineView) в методе -(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id‹MKOverlay›)overlay {   -  person Arun    schedule 21.07.2014
comment
@Spynet большое спасибо, теперь все работает отлично....   -  person iBeginner    schedule 21.07.2014
comment
@iBeginner всегда приветствуется, если ответ действительно помогает решить, тогда только принимайте   -  person Arun    schedule 21.07.2014
comment
@Spynet Добро пожаловать, сэр..   -  person iBeginner    schedule 21.07.2014
comment
@iBeginner не называйте меня, сэр, пожалуйста, удалите здесь, нет, сэр, или какая-либо разница, все или только то же самое .....   -  person Arun    schedule 21.07.2014


Ответы (1)


Попробуйте это.... это поможет вам...

-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{

        {
            self.routeLineView = [[MKPolylineView alloc] initWithPolyline:self.routeLine];
            self.routeLineView.strokeColor = [UIColor redColor];
            self.routeLineView.lineWidth = 5;
        }
        return self.routeLineView;
}
person Arun    schedule 21.07.2014