MKMapView не обновляет аннотации - PullRequest
1 голос
/ 07 февраля 2012

У меня есть MKMapView (очевидно), который показывает места размещения вокруг пользователя.

У меня есть инструмент Радиус, который, когда выбор сделан, аннотации должны быть добавлены / удалены в зависимости от расстояния вокруг пользователя.

У меня есть добавление / удаление штрафа, но по какой-то причине аннотации не будут отображаться, пока я не увеличу или уменьшу масштаб.

Это метод, который добавляет / удаляет аннотации на основе расстояния.Я попробовал два разных варианта метода.

  1. Добавляет новые аннотации в массив, а затем добавляет на карту [mapView addAnnotations:NSArray].

  2. Добавляет аннотации так, как находит их, используя[mapView addAnnotation:MKMapAnnotation];


1.

- (void)updateBasedDistance:(NSNumber *)distance {

    //Setup increment for HUD animation loading
    float hudIncrement = ( 1.0f / [[[[self appDelegate] rssParser]rssItems] count]);

    //Remove all the current annotations from the map
    [self._mapView removeAnnotations:self._mapView.annotations];

    //Hold all the new annotations to add to map
    NSMutableArray *tempAnnotations;

    /* 
     I have an array that holds all the annotations on the map becuase 
     a lot of filtering/searching happens. So for memory reasons it is
     more efficient to load annoations once then add/remove as needed.
    */
    for (int i = 0; i < [annotations count]; i++) {

        //Current annotations location
        CLLocation *tempLoc = [[CLLocation alloc] initWithLatitude:[[annotations objectAtIndex:i] coordinate].latitude longitude:[[annotations objectAtIndex:i] coordinate].longitude];

        //Distance of current annotaiton from user location converted to miles
        CLLocationDistance miles = [self._mapView.userLocation.location distanceFromLocation:tempLoc] * 0.000621371192;

        //If distance is less than user selection, add it to the map. 
        if (miles <= [distance floatValue]){
            if (tempAnnotations == nil)
                tempAnnotations = [[NSMutableArray alloc] init];
            [tempAnnotations addObject:[annotations objectAtIndex:i]];
        }

        //For some reason, even with ARC, helps a little with memory consumption
        tempLoc = nil;

        //Update a progress HUD I use. 
        HUD.progress += hudIncrement;
    }

    //Add the new annotaitons to the map
    if (tempAnnotations != nil)
        [self._mapView addAnnotations:tempAnnotations];
}

2.

- (void)updateBasedDistance:(NSNumber *)distance {

    //Setup increment for HUD animation loading
    float hudIncrement = ( 1.0f / [[[[self appDelegate] rssParser]rssItems] count]);

    //Remove all the current annotations from the map
    [self._mapView removeAnnotations:self._mapView.annotations];

    /* 
     I have an array that holds all the annotations on the map becuase 
     a lot of filtering/searching happens. So for memory reasons it is
     more efficient to load annoations once then add/remove as needed.
    */
    for (int i = 0; i < [annotations count]; i++) {

        //Current annotations location
        CLLocation *tempLoc = [[CLLocation alloc] initWithLatitude:[[annotations objectAtIndex:i] coordinate].latitude longitude:[[annotations objectAtIndex:i] coordinate].longitude];

        //Distance of current annotaiton from user location converted to miles
        CLLocationDistance miles = [self._mapView.userLocation.location distanceFromLocation:tempLoc] * 0.000621371192;

        //If distance is less than user selection, add it to the map. 
        if (miles <= [distance floatValue])
            [self._mapView addAnnotation:[annotations objectAtIndex:i]];

        //For some reason, even with ARC, helps a little with memory consumption
        tempLoc = nil;

        //Update a progress HUD I use. 
        HUD.progress += hudIncrement;
    }
}

Я также предпринял попыткуконец описанного выше метода:

[self._mapView setNeedsDisplay];
[self._mapView setNeedsLayout];

Кроме того, для принудительного обновления (где-то видел, что это может работать):

self._mapView.showsUserLocation = NO;
self._mapView.showsUserLocation = YES;

Любая помощь будет очень цениться и, как всегда, спасибоВы нашли время, чтобы прочитать.

1 Ответ

10 голосов
/ 07 февраля 2012

Я собираюсь догадаться, что updateBasedDistance: вызывается из фонового потока. Проверьте с NSLog(@"Am I in the UI thread? %d", [NSThread isMainThread]);. Если это 0, то вы должны переместить removeAnnotations: и addAnnotation: в вызов performSelectorOnMainThread: или с блоками GCD в главном потоке.

...