Search code examples
iosmkmapviewmkannotationcllocationpoint-of-interest

iOS SDK - Displaying # most important POIs at any displayed map range


I have a data structure, containing amongst others :

  • an NSNumber showing the importance of the POI (point of interest)
  • a CLLocation containing the coordinates of the POI.

Supposing I am able to order the POIs by importance and each POI has a unique importance factor, what is the best way to get a subarray with the POIs that are inside the displayed region in my MKMapView?

Simply checking every POI seems inefficient, as I may have a couple of thousands of POIs, and I want to repeat this process every time zoom level changes (so at any displayed region I show only the # most important ones).


Solution

  • I guess what you're looking for is :

    - (NSSet *)annotationsInMapRect:(MKMapRect)mapRect
    

    Quoting Apple documentation :

    This method offers a fast way to retrieve the annotation objects in a particular portion of the map. This method is much faster than doing a linear search of the objects in the annotations property yourself.

    Take care that's it's only Available in iOS 4.2 and later, I'm afraid there is no other solution than custom code in previous iOS versions.

    EDIT About your comment : My guess is that for a few thousands annotation, the above method should do the trick, MKAnnotation is a lightweight protocol, scanning an array by filtering on coordinate should be ok. But beware on not adding thousands of MKAnnotationView, that works on an iPhone 4, already did it, but you almost can't scroll map :)

    Then I would suggest :

    1. Use that method, quick to code, easy, then do some performance tests, on device
    2. If performances are not enough.... or you have to support prevous iOS versios, no magic, write you own code. (shouldn't be that hard, there are utility methods for converting regions and such)

    About memory, hey, these devices have easily at least 64MB free memory for your app, and will kill some processes if not, don't be scared by a few K of annotations! Just take care of memory leaks, especially on such intensive processes.