|Screenshot of Sample App|
I've created a project on GitHub - https://github.com/kazmiekr/MapPinClustering where you can download the code for the sample project. The sample project shows a map of a handful of annotations in the Boston area, you can zoom in and out and watch the pins animate to their locations. There are a bunch of pins in the downtown Boston area as well.
The core of the code is in the ClusteringMapView subclass of the MKMapView class that handles the logic of clustering the pins. Basically it divides the map into squares using the 'distance' property and while looping over the annotations, it only shows one pin per square. If there is already a pin displayed for that square, it sets that pin's cluster point to the shown pin. Each annotation is a custom MKAnnotation class that contains it's actual location and it's clustered point so we can animate the property as we show and hide the pins.
There is a lot you could do to improve this.
- You could try to do fancy measurement logic using meters/miles instead of random boxes to determine what to show, but at a cost to performance.
- You could get really fancy with a k-means clustering algorithm
- You could come up with weighted points to ensure that cluster points with a higher amount of points ensure visibility over others.
All of that is cool, but this works for now. Let me know what you think and I hope it's something you can use.