Проблема в создании нескольких маркеров в на карте, создает только последний. Какие варианты?

Использую Google Maps SDK for iOS 1.8.1. Код ниже. Создается только последний маркер. Непонятна причина.

@interface BanksViewController ()

@property (nonatomic, retain) CLLocationManager *locationManager;


@end

@implementation BanksViewController
{
GMSMapView *mapView_;

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu_icon.png"]
                                                                             style:UIBarButtonItemStyleBordered target:self action:@selector(showMenuViewController)];
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.title = @"Банкоматы и банки";
    
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    
    
    [self.locationManager startUpdatingLocation];
    
    CLLocation *location = [_locationManager location];
    CLLocationCoordinate2D coordinateCurrent = [location coordinate];
   
    
    
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithTarget:coordinateCurrent zoom:14];
    
    mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    
    
    
    GoogleMapsView.myLocationEnabled = YES;
    GoogleMapsView.settings.myLocationButton = YES;
    GoogleMapsView.camera = camera;
    
    GoogleMapsView.delegate = self;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        ParserDelegate* delegate = [ParserDelegate new];
        
        
        NSString* coordString = [[NSBundle mainBundle] pathForResource:@"coordinates" ofType:@"xml"];
        NSData *xmlData = [NSData dataWithContentsOfFile:coordString];
        
        
    NSXMLParser* parser = [[NSXMLParser alloc] initWithData:xmlData];
    [parser setDelegate:delegate];
    [parser parse];
    
    while ( ! delegate.done )
        sleep(1);
    
    if ( delegate.error == nil ) {
        
        NSArray *itemsAll=delegate.items;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
        for (int i=0; i<itemsAll.count; i++) {
        
           
           //сюда все приходит, проверил, массив из 7 словарей и берем dictionaty по i
            NSDictionary *temp=itemsAll[i];
            
            float latitude=[[temp objectForKey:@"latitude"] floatValue];
            float longitude=[[temp objectForKey:@"longitude"] floatValue];
            
            NSString *city=[temp objectForKey:@"city"];
            NSString *street=[temp objectForKey:@"street"];
            NSString *building=[temp objectForKey:@"building"];
            
            GMSMarker *marker = [GMSMarker markerWithPosition:CLLocationCoordinate2DMake(latitude, longitude)];
            
            marker.title =[temp objectForKey:@"name"];
            marker.snippet = [NSString stringWithFormat:@"%@, %@ %@", city,street,building];
            
            marker.map = GoogleMapsView;
            
          }
            
          GoogleMapsView=mapView_;
            
          });
            
            
        
        
    } else {
        // если была - выводим ошибку
        NSLog(@"Error: %@", delegate.error);
    }
    
    });
    
}



- (UIView*)mapView:(GMSMapView *)mapView markerInfoWindow:(GMSMarker *)marker {
    
    UIViewController *controller=[[UIViewController alloc] initWithNibName:@"CustomViewForATM" bundle:nil];
    CustomViewForATM *customView = (CustomViewForATM*)controller.view;
    [mapView_ addSubview:customView];
    return customView;
}


// метод, определяющий, что гуглокарты должны отображаться внутри вида GoogleMapsView на экране
- (void) setMapView:(GMSMapView *)mapView {
    if (!mapView) {
        mapView = [[GMSMapView alloc] initWithFrame:mapView.bounds];
    }
    GoogleMapsView = mapView;
}


@end


Итог- последний маркер стоит, остальные нет. пробовал не выделять память. Убирать инициализацию из цикла. Ничего не помогает. Ставит один маркер, а не 7.
  • Вопрос задан
  • 2488 просмотров
Решения вопроса 1
t-alexashka
@t-alexashka
Сразу пишу legacy код
Я в objective c не шарю, но могу предположить следующие возможные решения:

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

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы