iOS MapKit在一定距离内显示最近的注释

时间:2012-06-02 22:06:22

标签: ios5 mapkit xcode4.3 mkannotation

目前我正在开发基于位置的iPhone / iPad应用程序。我在MapKit中有几个注释,我想要做的是跟踪用户的位置并显示3公里内的注释。有人可以给我一个开始吗?

1 个答案:

答案 0 :(得分:1)

对不起延迟回复......这个问题刚刚落到我的视线中。

我将假设你有一个方法返回一组NSValue包装的CLLocationCoordinate2D结构(无论你的内部数据表示是什么,基本方法都是一样的)。然后,您可以使用类似于以下方法的方法过滤列表(警告:在浏览器中键入):

NSSet *locations = ...;
CLLocation centerLocation = ...; // Reference location for comparison, maybe from CLLocationManager
CLLocationDistance radius = 3000.; // Radius in meters
NSSet *nearbyLocations = [locations objectsPassingTest:^(id obj, BOOL *stop) {
        CLLocationCoordinate2D testCoordinate;
        [obj getValue:&testCoordinate];
        CLLocation *testLocation = [[CLLocation alloc] initWithLatitude:testCoordinate.latitude
                                                              longitude:testCoordinate.longitude];
        BOOL returnValue = ([centerLocation distanceFromLocation:testLocation] <= radius);
        [testLocation release];
        return returnValue;
    }
];

使用过滤后的坐标集,您可以创建MKAnnotation个实例,并按照常规方式将它们添加到地图中,如Apple's documentation中所述。

如果您有数千个测试位置,那么我认为这种方法可能会引发性能问题。然后,您需要切换要使用的点存储方法,例如quadtrees,以减少需要精确过滤的点数。但是不要过早优化!

希望有所帮助!

相关问题