RMQuadTree.m 24.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
//
//  RMQuadTree.m
//  MapView
//
// Copyright (c) 2008-2013, Route-Me Contributors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#import "RMQuadTree.h"
#import "RMAnnotation.h"
#import "RMProjection.h"
#import "RMMapView.h"

#pragma mark -
#pragma mark RMQuadTreeNode implementation

#define kMinimumQuadTreeElementWidth 200.0 // projected meters
#define kMaxAnnotationsPerLeaf 4
#define kMinPixelDistanceForLeafClustering 100.0

@interface RMAnnotation (RMQuadTree)

@property (nonatomic, assign) BOOL isClusterAnnotation;

@end

@interface RMQuadTreeNode ()

- (id)initWithMapView:(RMMapView *)aMapView forParent:(RMQuadTreeNode *)aParentNode inBoundingBox:(RMProjectedRect)aBoundingBox;

- (void)addAnnotation:(RMAnnotation *)annotation;
- (void)removeAnnotation:(RMAnnotation *)annotation;

- (void)addAnnotationsInBoundingBox:(RMProjectedRect)aBoundingBox
                     toMutableArray:(NSMutableArray *)someArray
           createClusterAnnotations:(BOOL)createClusterAnnotations
           withProjectedClusterSize:(RMProjectedSize)clusterSize
      andProjectedClusterMarkerSize:(RMProjectedSize)clusterMarkerSize
                  findGravityCenter:(BOOL)findGravityCenter;

- (void)removeUpwardsAllCachedClusterAnnotations;

- (void)precreateQuadTreeInBounds:(RMProjectedRect)quadTreeBounds withDepth:(NSUInteger)quadTreeDepth;

@end

@implementation RMQuadTreeNode
{
    RMProjectedRect _boundingBox, _northWestBoundingBox, _northEastBoundingBox, _southWestBoundingBox, _southEastBoundingBox;
    NSMutableArray *_annotations;
    RMQuadTreeNode *_parentNode, *_northWest, *_northEast, *_southWest, *_southEast;
    RMQuadTreeNodeType _nodeType;
    RMMapView *_mapView;

    RMAnnotation *_cachedClusterAnnotation;
    NSArray *_cachedClusterEnclosedAnnotations;
    NSMutableArray *_cachedEnclosedAnnotations, *_cachedUnclusteredAnnotations;
}

@synthesize nodeType = _nodeType;
@synthesize boundingBox = _boundingBox;
@synthesize northWestBoundingBox = _northWestBoundingBox, northEastBoundingBox = _northEastBoundingBox;
@synthesize southWestBoundingBox = _southWestBoundingBox, southEastBoundingBox = _southEastBoundingBox;
@synthesize parentNode = _parentNode;
@synthesize northWest = _northWest, northEast = _northEast;
@synthesize southWest = _southWest, southEast = _southEast;

- (id)initWithMapView:(RMMapView *)aMapView forParent:(RMQuadTreeNode *)aParentNode inBoundingBox:(RMProjectedRect)aBoundingBox
{
    if (!(self = [super init]))
        return nil;

//    RMLog(@"New quadtree node at {(%.0f,%.0f),(%.0f,%.0f)}", aBoundingBox.origin.easting, aBoundingBox.origin.northing, aBoundingBox.size.width, aBoundingBox.size.height);

    _mapView = aMapView;
    _parentNode = aParentNode;
    _northWest = _northEast = _southWest = _southEast = nil;
    _annotations = [NSMutableArray new];
    _boundingBox = aBoundingBox;
    _cachedClusterAnnotation = nil;
    _cachedClusterEnclosedAnnotations = nil;
    _cachedEnclosedAnnotations = _cachedUnclusteredAnnotations = nil;

    double halfWidth = _boundingBox.size.width / 2.0, halfHeight = _boundingBox.size.height / 2.0;
    _northWestBoundingBox = RMProjectedRectMake(_boundingBox.origin.x, _boundingBox.origin.y + halfHeight, halfWidth, halfHeight);
    _northEastBoundingBox = RMProjectedRectMake(_boundingBox.origin.x + halfWidth, _boundingBox.origin.y + halfHeight, halfWidth, halfHeight);
    _southWestBoundingBox = RMProjectedRectMake(_boundingBox.origin.x, _boundingBox.origin.y, halfWidth, halfHeight);
    _southEastBoundingBox = RMProjectedRectMake(_boundingBox.origin.x + halfWidth, _boundingBox.origin.y, halfWidth, halfHeight);

    _nodeType = nodeTypeLeaf;

    return self;
}

- (void)dealloc
{
    _mapView = nil;

    @synchronized (_cachedClusterAnnotation)
    {
         _cachedClusterEnclosedAnnotations = nil;
         _cachedClusterAnnotation = nil;
    }

    @synchronized (_annotations)
    {
        for (RMAnnotation *annotation in _annotations)
        {
            annotation.quadTreeNode = nil;
        }
    }
}

- (NSArray *)annotations
{
    NSArray *immutableAnnotations = nil;

    @synchronized (_annotations)
    {
        immutableAnnotations = [NSArray arrayWithArray:_annotations];
    }

    return immutableAnnotations;
}

- (void)addAnnotationToChildNodes:(RMAnnotation *)annotation
{
    RMProjectedRect projectedRect = annotation.projectedBoundingBox;

    if (RMProjectedRectContainsProjectedRect(_northWestBoundingBox, projectedRect))
    {
        if (!_northWest)
            _northWest = [[RMQuadTreeNode alloc] initWithMapView:_mapView forParent:self inBoundingBox:_northWestBoundingBox];

        [_northWest addAnnotation:annotation];
    }
    else if (RMProjectedRectContainsProjectedRect(_northEastBoundingBox, projectedRect))
    {
        if (!_northEast)
            _northEast = [[RMQuadTreeNode alloc] initWithMapView:_mapView forParent:self inBoundingBox:_northEastBoundingBox];

        [_northEast addAnnotation:annotation];
    }
    else if (RMProjectedRectContainsProjectedRect(_southWestBoundingBox, projectedRect))
    {
        if (!_southWest)
            _southWest = [[RMQuadTreeNode alloc] initWithMapView:_mapView forParent:self inBoundingBox:_southWestBoundingBox];

        [_southWest addAnnotation:annotation];
    }
    else if (RMProjectedRectContainsProjectedRect(_southEastBoundingBox, projectedRect))
    {
        if (!_southEast)
            _southEast = [[RMQuadTreeNode alloc] initWithMapView:_mapView forParent:self inBoundingBox:_southEastBoundingBox];

        [_southEast addAnnotation:annotation];
    }
    else
    {
        @synchronized (_annotations)
        {
            [_annotations addObject:annotation];
        }

        annotation.quadTreeNode = self;
        [self removeUpwardsAllCachedClusterAnnotations];
    }
}

- (void)precreateQuadTreeInBounds:(RMProjectedRect)quadTreeBounds withDepth:(NSUInteger)quadTreeDepth
{
    if (quadTreeDepth == 0 || _boundingBox.size.width < (kMinimumQuadTreeElementWidth * 2.0))
        return;

//    RMLog(@"node in {%.0f,%.0f},{%.0f,%.0f} depth %d", boundingBox.origin.x, boundingBox.origin.y, boundingBox.size.width, boundingBox.size.height, quadTreeDepth);

    @synchronized (_cachedClusterAnnotation)
    {
         _cachedClusterEnclosedAnnotations = nil;
         _cachedClusterAnnotation = nil;
    }

    if (RMProjectedRectIntersectsProjectedRect(quadTreeBounds, _northWestBoundingBox))
    {
        if (!_northWest)
            _northWest = [[RMQuadTreeNode alloc] initWithMapView:_mapView forParent:self inBoundingBox:_northWestBoundingBox];

        [_northWest precreateQuadTreeInBounds:quadTreeBounds withDepth:quadTreeDepth-1];
    }

    if (RMProjectedRectIntersectsProjectedRect(quadTreeBounds, _northEastBoundingBox))
    {
        if (!_northEast)
            _northEast = [[RMQuadTreeNode alloc] initWithMapView:_mapView forParent:self inBoundingBox:_northEastBoundingBox];

        [_northEast precreateQuadTreeInBounds:quadTreeBounds withDepth:quadTreeDepth-1];
    }

    if (RMProjectedRectIntersectsProjectedRect(quadTreeBounds, _southWestBoundingBox))
    {
        if (!_southWest)
            _southWest = [[RMQuadTreeNode alloc] initWithMapView:_mapView forParent:self inBoundingBox:_southWestBoundingBox];

        [_southWest precreateQuadTreeInBounds:quadTreeBounds withDepth:quadTreeDepth-1];
    }

    if (RMProjectedRectIntersectsProjectedRect(quadTreeBounds, _southEastBoundingBox))
    {
        if (!_southEast)
            _southEast = [[RMQuadTreeNode alloc] initWithMapView:_mapView forParent:self inBoundingBox:_southEastBoundingBox];

        [_southEast precreateQuadTreeInBounds:quadTreeBounds withDepth:quadTreeDepth-1];
    }

    if (_nodeType == nodeTypeLeaf && [_annotations count])
    {
        NSArray *immutableAnnotations = nil;

        @synchronized (_annotations)
        {
            immutableAnnotations = [NSArray arrayWithArray:_annotations];
            [_annotations removeAllObjects];
        }

        for (RMAnnotation *annotationToMove in immutableAnnotations)
        {
            [self addAnnotationToChildNodes:annotationToMove];
        }
    }

    _nodeType = nodeTypeNode;
}

- (void)addAnnotation:(RMAnnotation *)annotation
{
    if (_nodeType == nodeTypeLeaf)
    {
        @synchronized (_annotations)
        {
            [_annotations addObject:annotation];
        }

        annotation.quadTreeNode = self;

        if ([_annotations count] <= kMaxAnnotationsPerLeaf || _boundingBox.size.width < (kMinimumQuadTreeElementWidth * 2.0))
        {
            [self removeUpwardsAllCachedClusterAnnotations];
            return;
        }

        _nodeType = nodeTypeNode;

        // problem: all annotations that cross two quadrants will always be re-added here, which
        // might be a problem depending on kMaxAnnotationsPerLeaf

        NSArray *immutableAnnotations = nil;

        @synchronized (_annotations)
        {
            immutableAnnotations = [NSArray arrayWithArray:_annotations];
            [_annotations removeAllObjects];
        }

        for (RMAnnotation *annotationToMove in immutableAnnotations)
        {
            [self addAnnotationToChildNodes:annotationToMove];
        }

        return;
    }

    [self addAnnotationToChildNodes:annotation];
}

- (void)removeAnnotation:(RMAnnotation *)annotation
{
    if (!annotation.quadTreeNode)
        return;

    annotation.quadTreeNode = nil;

    @synchronized (_annotations)
    {
        [_annotations removeObject:annotation];
    }

    [self removeUpwardsAllCachedClusterAnnotations];
}

- (void)annotationDidChangeBoundingBox:(RMAnnotation *)annotation
{
    if (RMProjectedRectContainsProjectedRect(_boundingBox, annotation.projectedBoundingBox))
        return;

    [self removeAnnotation:annotation];

    RMQuadTreeNode *nextParentNode = self;

    while ((nextParentNode = [nextParentNode parentNode]))
    {
        if (RMProjectedRectContainsProjectedRect(nextParentNode.boundingBox, annotation.projectedBoundingBox))
        {
            [nextParentNode addAnnotationToChildNodes:annotation];
            break;
        }
    }
}

- (NSArray *)enclosedAnnotations
{
    if (!_cachedEnclosedAnnotations)
    {
        _cachedEnclosedAnnotations = [[NSMutableArray alloc] initWithArray:self.annotations];
        if (_northWest) [_cachedEnclosedAnnotations addObjectsFromArray:_northWest.enclosedAnnotations];
        if (_northEast) [_cachedEnclosedAnnotations addObjectsFromArray:_northEast.enclosedAnnotations];
        if (_southWest) [_cachedEnclosedAnnotations addObjectsFromArray:_southWest.enclosedAnnotations];
        if (_southEast) [_cachedEnclosedAnnotations addObjectsFromArray:_southEast.enclosedAnnotations];
    }

    return _cachedEnclosedAnnotations;
}

- (NSArray *)unclusteredAnnotations
{
    if (!_cachedUnclusteredAnnotations)
    {
        _cachedUnclusteredAnnotations = [NSMutableArray new];

        @synchronized (_annotations)
        {
            for (RMAnnotation *annotation in _annotations)
            {
                if (!annotation.clusteringEnabled)
                    [_cachedUnclusteredAnnotations addObject:annotation];
            }
        }

        if (_northWest) [_cachedUnclusteredAnnotations addObjectsFromArray:[_northWest unclusteredAnnotations]];
        if (_northEast) [_cachedUnclusteredAnnotations addObjectsFromArray:[_northEast unclusteredAnnotations]];
        if (_southWest) [_cachedUnclusteredAnnotations addObjectsFromArray:[_southWest unclusteredAnnotations]];
        if (_southEast) [_cachedUnclusteredAnnotations addObjectsFromArray:[_southEast unclusteredAnnotations]];
    }

    return _cachedUnclusteredAnnotations;
}

- (NSArray *)enclosedWithoutUnclusteredAnnotations
{
    NSArray *unclusteredAnnotations = self.unclusteredAnnotations;
    if (!unclusteredAnnotations || [unclusteredAnnotations count] == 0)
        return self.enclosedAnnotations;

    NSMutableArray *enclosedAnnotations = [NSMutableArray arrayWithArray:self.enclosedAnnotations];
    [enclosedAnnotations removeObjectsInArray:unclusteredAnnotations];

    return enclosedAnnotations;
}

- (RMAnnotation *)clusterAnnotation
{
    return _cachedClusterAnnotation;
}

- (NSArray *)clusteredAnnotations
{
    NSArray *clusteredAnnotations = nil;

    @synchronized (_cachedClusterAnnotation)
    {
        clusteredAnnotations = [NSArray arrayWithArray:_cachedClusterEnclosedAnnotations];
    }

    return clusteredAnnotations;
}

- (void)addAnnotationsInBoundingBox:(RMProjectedRect)aBoundingBox
                     toMutableArray:(NSMutableArray *)someArray
           createClusterAnnotations:(BOOL)createClusterAnnotations
           withProjectedClusterSize:(RMProjectedSize)clusterSize
      andProjectedClusterMarkerSize:(RMProjectedSize)clusterMarkerSize
                  findGravityCenter:(BOOL)findGravityCenter
{
    if (createClusterAnnotations)
    {
        double halfWidth     = _boundingBox.size.width / 2.0;
        BOOL forceClustering = (_boundingBox.size.width >= clusterSize.width && halfWidth < clusterSize.width);

        NSArray *enclosedAnnotations = nil;

        // Leaf clustering
        if (forceClustering == NO && _nodeType == nodeTypeLeaf && [_annotations count] > 1)
        {
            NSMutableArray *annotationsToCheck = [NSMutableArray arrayWithArray:[self enclosedWithoutUnclusteredAnnotations]];

            for (NSInteger i=[annotationsToCheck count]-1; i>0; --i)
            {
                BOOL mustBeClustered = NO;
                RMAnnotation *currentAnnotation = [annotationsToCheck objectAtIndex:i];

                for (NSInteger j=i-1; j>=0; --j)
                {
                    RMAnnotation *secondAnnotation = [annotationsToCheck objectAtIndex:j];

                    // This is of course not very accurate but is good enough for this use case
                    double distance = RMEuclideanDistanceBetweenProjectedPoints(currentAnnotation.projectedLocation, secondAnnotation.projectedLocation) / _mapView.metersPerPixel;
                    if (distance < kMinPixelDistanceForLeafClustering)
                    {
                        mustBeClustered = YES;
                        break;
                    }
                }

                if (!mustBeClustered)
                {
                    [someArray addObject:currentAnnotation];
                    [annotationsToCheck removeObjectAtIndex:i];
                }
            }

            forceClustering = ([annotationsToCheck count] > 0);

            if (forceClustering)
            {
                @synchronized (_cachedClusterAnnotation)
                {
                     _cachedClusterEnclosedAnnotations = nil;
                     _cachedClusterAnnotation = nil;
                }

                enclosedAnnotations = [NSArray arrayWithArray:annotationsToCheck];
            }
        }

        if (forceClustering)
        {
            if (!enclosedAnnotations)
                enclosedAnnotations = [self enclosedWithoutUnclusteredAnnotations];

            @synchronized (_cachedClusterAnnotation)
            {
                if (_cachedClusterAnnotation && [enclosedAnnotations count] != [_cachedClusterEnclosedAnnotations count])
                {
                     _cachedClusterEnclosedAnnotations = nil;
                     _cachedClusterAnnotation = nil;
                }
            }

            if (!_cachedClusterAnnotation)
            {
                NSUInteger enclosedAnnotationsCount = [enclosedAnnotations count];

                if (enclosedAnnotationsCount < 2)
                {
                    @synchronized (_annotations)
                    {
                        [someArray addObjectsFromArray:enclosedAnnotations];
                        [someArray addObjectsFromArray:[self unclusteredAnnotations]];
                    }

                    return;
                }

                RMProjectedPoint clusterMarkerPosition;

                if (findGravityCenter)
                {
                    double averageX = 0.0, averageY = 0.0;

                    for (RMAnnotation *annotation in enclosedAnnotations)
                    {
                        averageX += annotation.projectedLocation.x;
                        averageY += annotation.projectedLocation.y;
                    }

                    averageX /= (double)enclosedAnnotationsCount;
                    averageY /= (double)enclosedAnnotationsCount;

                    double halfClusterMarkerWidth = clusterMarkerSize.width / 2.0,
                           halfClusterMarkerHeight = clusterMarkerSize.height / 2.0;

                    if (averageX - halfClusterMarkerWidth < _boundingBox.origin.x)
                        averageX = _boundingBox.origin.x + halfClusterMarkerWidth;
                    if (averageX + halfClusterMarkerWidth > _boundingBox.origin.x + _boundingBox.size.width)
                        averageX = _boundingBox.origin.x + _boundingBox.size.width - halfClusterMarkerWidth;
                    if (averageY - halfClusterMarkerHeight < _boundingBox.origin.y)
                        averageY = _boundingBox.origin.y + halfClusterMarkerHeight;
                    if (averageY + halfClusterMarkerHeight > _boundingBox.origin.y + _boundingBox.size.height)
                        averageY = _boundingBox.origin.y + _boundingBox.size.height - halfClusterMarkerHeight;

                    // TODO: anchorPoint
                    clusterMarkerPosition = RMProjectedPointMake(averageX, averageY);
                }
                else
                {
                    clusterMarkerPosition = RMProjectedPointMake(_boundingBox.origin.x + halfWidth, _boundingBox.origin.y + (_boundingBox.size.height / 2.0));
                }

                CLLocationCoordinate2D clusterMarkerCoordinate = [[_mapView projection] projectedPointToCoordinate:clusterMarkerPosition];

                _cachedClusterAnnotation = [[RMAnnotation alloc] initWithMapView:_mapView
                                                                     coordinate:clusterMarkerCoordinate
                                                                       andTitle:[NSString stringWithFormat:@"%d", enclosedAnnotationsCount]];
                _cachedClusterAnnotation.isClusterAnnotation = YES;
                _cachedClusterAnnotation.userInfo = self;

                _cachedClusterEnclosedAnnotations = [[NSArray alloc] initWithArray:enclosedAnnotations];
            }

            [someArray addObject:_cachedClusterAnnotation];
            [someArray addObjectsFromArray:[self unclusteredAnnotations]];

            return;
        }

        if (_nodeType == nodeTypeLeaf)
        {
            @synchronized (_annotations)
            {
                [someArray addObjectsFromArray:_annotations];
            }

            return;
        }
    }
    else
    {
        if (_nodeType == nodeTypeLeaf)
        {
            @synchronized (_annotations)
            {
                [someArray addObjectsFromArray:_annotations];
            }

            return;
        }
    }

    if (RMProjectedRectIntersectsProjectedRect(aBoundingBox, _northWestBoundingBox))
        [_northWest addAnnotationsInBoundingBox:aBoundingBox toMutableArray:someArray createClusterAnnotations:createClusterAnnotations withProjectedClusterSize:clusterSize andProjectedClusterMarkerSize:clusterMarkerSize findGravityCenter:findGravityCenter];
    if (RMProjectedRectIntersectsProjectedRect(aBoundingBox, _northEastBoundingBox))
        [_northEast addAnnotationsInBoundingBox:aBoundingBox toMutableArray:someArray createClusterAnnotations:createClusterAnnotations withProjectedClusterSize:clusterSize andProjectedClusterMarkerSize:clusterMarkerSize findGravityCenter:findGravityCenter];
    if (RMProjectedRectIntersectsProjectedRect(aBoundingBox, _southWestBoundingBox))
        [_southWest addAnnotationsInBoundingBox:aBoundingBox toMutableArray:someArray createClusterAnnotations:createClusterAnnotations withProjectedClusterSize:clusterSize andProjectedClusterMarkerSize:clusterMarkerSize findGravityCenter:findGravityCenter];
    if (RMProjectedRectIntersectsProjectedRect(aBoundingBox, _southEastBoundingBox))
        [_southEast addAnnotationsInBoundingBox:aBoundingBox toMutableArray:someArray createClusterAnnotations:createClusterAnnotations withProjectedClusterSize:clusterSize andProjectedClusterMarkerSize:clusterMarkerSize findGravityCenter:findGravityCenter];

    @synchronized (_annotations)
    {
        for (RMAnnotation *annotation in _annotations)
        {
            if (RMProjectedRectIntersectsProjectedRect(aBoundingBox, annotation.projectedBoundingBox))
                [someArray addObject:annotation];
        }
    }
}

- (void)removeUpwardsAllCachedClusterAnnotations
{
    if (_parentNode)
        [_parentNode removeUpwardsAllCachedClusterAnnotations];

    @synchronized (_cachedClusterAnnotation)
    {
         _cachedClusterEnclosedAnnotations = nil;
         _cachedClusterAnnotation = nil;
    }

     _cachedEnclosedAnnotations = nil;
     _cachedUnclusteredAnnotations = nil;
}

@end

#pragma mark - RMQuadTree implementation

@implementation RMQuadTree
{
    RMQuadTreeNode *_rootNode;
    RMMapView *_mapView;
}

- (id)initWithMapView:(RMMapView *)aMapView
{
    if (!(self = [super init]))
        return nil;

    _mapView = aMapView;
    _rootNode = [[RMQuadTreeNode alloc] initWithMapView:_mapView forParent:nil inBoundingBox:[[RMProjection googleProjection] planetBounds]];

    return self;
}

- (void)addAnnotation:(RMAnnotation *)annotation
{
    @synchronized (self)
    {
        if ( ! [_rootNode.annotations containsObject:annotation])
            [_rootNode addAnnotation:annotation];
    }
}

- (void)addAnnotations:(NSArray *)annotations
{
//    RMLog(@"Prepare tree");
//    [rootNode precreateQuadTreeInBounds:[[RMProjection googleProjection] planetBounds] withDepth:5];

    @synchronized (self)
    {
        for (RMAnnotation *annotation in annotations)
            if ( ! [_rootNode.annotations containsObject:annotation])
                [_rootNode addAnnotation:annotation];
    }
}

- (void)removeAnnotation:(RMAnnotation *)annotation
{
    @synchronized (self)
    {
        [annotation.quadTreeNode removeAnnotation:annotation];
    }
}

- (void)removeAllObjects
{
    @synchronized (self)
    {
        _rootNode = [[RMQuadTreeNode alloc] initWithMapView:_mapView forParent:nil inBoundingBox:[[RMProjection googleProjection] planetBounds]];
    }
}

#pragma mark -

- (NSArray *)annotationsInProjectedRect:(RMProjectedRect)boundingBox
{
    return [self annotationsInProjectedRect:boundingBox createClusterAnnotations:NO withProjectedClusterSize:RMProjectedSizeMake(0.0, 0.0) andProjectedClusterMarkerSize:RMProjectedSizeMake(0.0, 0.0) findGravityCenter:NO];
}

- (NSArray *)annotationsInProjectedRect:(RMProjectedRect)boundingBox createClusterAnnotations:(BOOL)createClusterAnnotations withProjectedClusterSize:(RMProjectedSize)clusterSize andProjectedClusterMarkerSize:(RMProjectedSize)clusterMarkerSize findGravityCenter:(BOOL)findGravityCenter
{
    NSMutableArray *annotations = [NSMutableArray array];

    @synchronized (self)
    {
        [_rootNode addAnnotationsInBoundingBox:boundingBox toMutableArray:annotations createClusterAnnotations:createClusterAnnotations withProjectedClusterSize:clusterSize andProjectedClusterMarkerSize:clusterMarkerSize findGravityCenter:findGravityCenter];
    }

    return annotations;
}

@end