2014-05-23 5 views
1

У меня возникла проблема с цветом mkoverlay. Когда я открываю карту, иногда вместо того, чтобы рисовать пешеходную дорожку, он окрашивается с велосипедной активностью. Я не знаю, как решить проблему. Несмотря на то, что я не занимался велосипедным спортом, он привлекает велосипедную деятельность синим цветом. enter image description hereMapView Overlay Drawing

Вот реализация кода.

- (void)showLines { 

    NSUserDefaults *def = [NSUserDefaults standardUserDefaults]; 

    NSArray* coordinate_array = [[NSArray alloc] init]; 
    int arrayCount = 0; 
     // walking 
    NSData *data =[def objectForKey:@"walking_coordinate"]; 
    NSMutableArray *walking_array = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 
    coordinate_array = [NSArray arrayWithArray:walking_array]; 
    arrayCount = (int)[walking_array count]; 
    color = 1; 
    [self parseArray:coordinate_array withArrayCount:arrayCount]; 

     // driving 
    data =[def objectForKey:@"driving_coordinate"]; 
    NSMutableArray *driving_array = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 
    coordinate_array = [NSArray arrayWithArray:driving_array]; 
    arrayCount = (int)[driving_array count]; 
    color = 2; 
    [self parseArray:coordinate_array withArrayCount:arrayCount]; 

     // biking 
    data =[def objectForKey:@"biking_coordinate"]; 
    NSMutableArray *biking_array = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 
    coordinate_array = [NSArray arrayWithArray:biking_array]; 
    arrayCount = (int)[biking_array count]; 
    color = 3; 
    [self parseArray:coordinate_array withArrayCount:arrayCount]; 

} 

- (void) parseArray:(NSArray *) coordinate_array withArrayCount:(int)arrayCount 
{ 
    NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:0]; 

    for (int i = 0; i < arrayCount; i++) { 
     CoordinateModel *coord = [coordinate_array objectAtIndex:i]; 
     [tempArray addObject:coord]; 

     if ((int)coord.latitude == -1 || (int)coord.longitude == -1 || i == arrayCount-1) { 
      // this is end of one segment 
      [tempArray removeLastObject]; 
      CLLocationCoordinate2D *pointsCoordinate = (CLLocationCoordinate2D *)malloc(sizeof(CLLocationCoordinate2D) * [tempArray count]); 

      for (int j = 0; j < [tempArray count]; j++) { 
       CoordinateModel *point = [tempArray objectAtIndex:j]; 
       CLLocationCoordinate2D old_coordinate = CLLocationCoordinate2DMake(point.latitude, point.longitude); 
       pointsCoordinate[j] = old_coordinate; 
      // NSLog(@"(%f, %f)", old_coordinate.latitude, old_coordinate.longitude); 
      } 
      if ([tempArray count] > 0) { 
       int countTemp = (int)[tempArray count]; 
       MKPolyline *polyline = [MKPolyline polylineWithCoordinates:pointsCoordinate count:countTemp]; 
       [mapView addOverlay:polyline]; 
       [tempArray removeAllObjects]; 
      } 
     } 
    } 

} 

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay 
{ 
    if([overlay isKindOfClass:[MKPolyline class]]) 
    { 
     MKPolylineView *lineView = [[MKPolylineView alloc] initWithPolyline:overlay]; 
     lineView.lineWidth = 8; 

     if (color == 1) { 
      // walking 
      lineView.strokeColor = [UIColor greenColor]; 
      lineView.fillColor = [UIColor greenColor]; 
     } 
     else if(color == 2) { 
      // driving 
      lineView.strokeColor = [UIColor redColor]; 
      lineView.fillColor = [UIColor redColor]; 
     } 
     else if(color == 3) { 
      // biking 
      lineView.strokeColor = [UIColor blueColor]; 
      lineView.fillColor = [UIColor blueColor]; 
     } 
     else { 
      lineView.strokeColor = [UIColor blackColor]; 
      lineView.fillColor = [UIColor blackColor]; 
     } 

     return lineView; 
    } 
    return nil; 
} 

ответ

0

В методе viewForOverlay делегата, цвет наложения устанавливается с помощью внешней переменной color, который установлен перед вызовом parseArray для каждого типа наложения.

Однако, нет никакой гарантии, когда метод делегата будет вызываться видом карты, и это возможно метод делегата будет вызываться несколько раз для одной и того же наложения после ужедобавленных всех оверлеев (например, если вы увеличиваете/панорамируете карту, и наложение возвращается в поле зрения).

С момента последнего установленного значения color значение «3» (для «езды на велосипеде»), любые вызовы, которые вид карты отображает на метод делегата после добавления наложения, в конечном итоге будут рисовать оверлей с цветным цветом.


Чтобы исправить это, вы должны быть в состоянии определить, какой цвет, чтобы нарисовать overlay внутри самого метода делегата, используя некоторое свойство параметра overlay (а не полагаться на какой-либо внешней переменной).

Самый простой способ использовать это свойство MKPolylinetitle.
См. this answer и this answer, которые объясняют тот факт, что MKPolyline имеет title.

Так что вы могли сделать в вашем случае:

  1. Сделать color параметр, который вы передаете ваш метод parseArray.
  2. В методе parseArray, после создания polyline, установите его title цвета:

    polyline.title = [NSString stringWithFormat:@"%d", color]; 
    
  3. В viewForOverlay, проверьте title свойства наложения и установите цвет соответственно. См. Конкретный пример в different coloured polygon overlays (он показывает его для многоугольника, но то же самое можно сделать с помощью полилиний).

+0

Огромное спасибо Анне, за предоставление очень подробного ответа, как всегда. –

+0

Я был бы рад, если бы у вас было время, чтобы помочь мне задать еще один вопрос, который я недавно опубликовал http://stackoverflow.com/questions/23820252/cllocationmanager-coordinates –

+0

Анна, я была бы счастлива, если бы вы смогли взглянуть мой вопрос, связанный с вашим опытом. http://stackoverflow.com/questions/23833758/gps-coordinate-accuracy –

0

Вот ответ, основанный на ответе Анны, чтобы помочь кому угодно видеть в коде.

- (void)showLines2 { 


     NSUserDefaults *def = [NSUserDefaults standardUserDefaults]; 

     NSArray* coordinate_array = [[NSArray alloc] init]; 
     int arrayCount = 0; 
      // walking 
     NSData *data =[def objectForKey:@"walking_coordinate"]; 
     NSMutableArray *walking_array = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 
     coordinate_array = [NSArray arrayWithArray:walking_array]; 
     arrayCount = (int)[walking_array count]; 
     color = 1; 
     [self parseArray:coordinate_array withArrayCount:arrayCount withColor:color]; 

      // driving 
     data =[def objectForKey:@"driving_coordinate"]; 
     NSMutableArray *driving_array = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 
     coordinate_array = [NSArray arrayWithArray:driving_array]; 
     arrayCount = (int)[driving_array count]; 
     color = 2; 
     [self parseArray:coordinate_array withArrayCount:arrayCount withColor:color]; 

      // biking 
     data =[def objectForKey:@"biking_coordinate"]; 
     NSMutableArray *biking_array = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 
     coordinate_array = [NSArray arrayWithArray:biking_array]; 
     arrayCount = (int)[biking_array count]; 
     color = 3; 
     [self parseArray:coordinate_array withArrayCount:arrayCount withColor:color]; 

    } 


- (void) parseArray:(NSArray *) coordinate_array withArrayCount:(int)arrayCount withColor:(int)polyColor 
{ 
    NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:0]; 

    for (int i = 0; i < arrayCount; i++) { 
     CoordinateModel *coord = [coordinate_array objectAtIndex:i]; 
     [tempArray addObject:coord]; 

     if ((int)coord.latitude == -1 || (int)coord.longitude == -1 || i == arrayCount-1) { 
      // this is end of one segment 
      [tempArray removeLastObject]; 
      CLLocationCoordinate2D *pointsCoordinate = (CLLocationCoordinate2D *)malloc(sizeof(CLLocationCoordinate2D) * [tempArray count]); 

      for (int j = 0; j < [tempArray count]; j++) { 
       CoordinateModel *point = [tempArray objectAtIndex:j]; 
       CLLocationCoordinate2D old_coordinate = CLLocationCoordinate2DMake(point.latitude, point.longitude); 
       pointsCoordinate[j] = old_coordinate; 
      // NSLog(@"(%f, %f)", old_coordinate.latitude, old_coordinate.longitude); 
      } 
      if ([tempArray count] > 0) { 
       int countTemp = (int)[tempArray count]; 
       MKPolyline *polyline = [MKPolyline polylineWithCoordinates:pointsCoordinate count:countTemp]; 
       polyline.title = [NSString stringWithFormat:@"%d", color]; 
       [mapView addOverlay:polyline]; 
       [tempArray removeAllObjects]; 
      } 
     } 
    } 

} 

    - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay 
    { 
     if([overlay isKindOfClass:[MKPolyline class]]) 
     { 
      MKPolylineView *lineView = [[MKPolylineView alloc] initWithPolyline:overlay]; 
      lineView.lineWidth = 8; 

    //  ActivityType currentActivityType = [DataManager sharedInstance].activityType; 
      if ([overlay.title isEqualToString:@"1"]) { 
       // walking 
       lineView.strokeColor = [UIColor greenColor]; 
       lineView.fillColor = [UIColor greenColor]; 
      } 
      else if([overlay.title isEqualToString:@"2"]) { 
       // driving 
       lineView.strokeColor = [UIColor redColor]; 
       lineView.fillColor = [UIColor redColor]; 
      } 
      else if([overlay.title isEqualToString:@"3"]) { 
       // biking 
       lineView.strokeColor = [UIColor blueColor]; 
       lineView.fillColor = [UIColor blueColor]; 
      } 
      else { 
       lineView.strokeColor = [UIColor blackColor]; 
       lineView.fillColor = [UIColor blackColor]; 
      } 

      return lineView; 
     } 
     return nil; 
    } 
Смежные вопросы