iPhone MKMapView Annotation Clustering

haluzak picture haluzak · Oct 18, 2011 · Viewed 22.5k times · Source

I've got quite a lot of pins to put on my map so I think it would be a nice idea to cluster those annotations. I'm not really sure how to achieve this on iPhone, I was able to work something out with google maps and some javascript examples. But iPhone uses its mkmapview and I have no idea how to cluster annotations in there.

Any ideas or frameworks that you know and are good? Thanks.

Answer

eric picture eric · Mar 15, 2013

You don't necessarily need to use a 3rd party framework because since iOS 4.2, MKMapView has a method called - (NSSet *)annotationsInMapRect:(MKMapRect)mapRect which you can use to do your clustering.

Check out the WWDC11 Session video 'Visualizing Information Geographically with MapKit'. About half way through it explains how to do it. But I'll summarize the concept for you:

  • Use Two maps (second map is never added to the view hierarchy)
  • Second map contains all annotations (again, it's never drawn)
  • Divide map area into a grid of squares
  • Use -annotationsInMapRect method to get annotation data from invisible map
  • Visible map builds its annotations from this data from invisible map

enter image description here