iOS MapKit show nearest annotations within certain distance

自古美人都是妖i 提交于 2019-12-01 10:30:13

问题


Currently i am working on a Location based application for iPhone/iPad . I have several annotations in my MapKit , what i want to do is to track the location of the user and shows the annotations that are within the 3km . Can somebody give me a start ?


回答1:


Sorry for the delayed response... the question just fell off my radar.

I'm going to suppose that you have a method that returns a set of NSValue-wrapped CLLocationCoordinate2D structs (the basic approach is the same regardless of what your internal data representations are). You can then filter the list using a method something akin to the following (warning: typed in browser):

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;
    }
];

With the filtered set of coordinates in hand, you can create MKAnnotation instances and add them to the map in the usual manner, as described in Apple's documentation.

If you have many thousands of test locations then I suppose this approach could start to incur performance issues. You would then want to switch your point storage approach to use, e.g., quadtrees, to reduce the number of points that need to be precision-filtered. But don't optimize prematurely!

Hope that helps!



来源:https://stackoverflow.com/questions/10866297/ios-mapkit-show-nearest-annotations-within-certain-distance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!