I have an NSArray of 500 annotations, and I basically want to show only the ten closest annotations to the user (the rest will not be added to Mapview)
How should I do it?
Here is my code:
-(void) loadAndSortPOIs {
[poiArray release];
nextPoiIndex = 0;
NSString *poiPath = [[NSBundle mainBundle] pathForResource:@"annotations"
ofType:@"plist"];
poiArray = [[NSMutableArray alloc] initWithContentsOfFile:poiPath];
CLLocation *homeLocation = [[CLLocation alloc]
initWithLatitude:homeCoordinate.latitude
longitude:homeCoordinate.longitude];
for (int i = 0; i < [poiArray count]; i++) {
NSDictionary *dict = (NSDictionary*) [poiArray objectAtIndex: i];
CLLocationDegrees storeLatitude = [[dict objectForKey:@"workingCoordinate.latitude"] doubleValue];
CLLocationDegrees storeLongitude = [[dict objectForKey:@"workingCoordinate.longitude"] doubleValue];
CLLocation *storeLocation = [[CLLocation alloc]
initWithLatitude:storeLatitude
longitude:storeLongitude];
CLLocationDistance distanceFromHome = [storeLocation distanceFromLocation: homeLocation];
[storeLocation release];
NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc]
initWithDictionary:dict];
[mutableDict setValue:[NSNumber numberWithDouble:distanceFromHome]
forKey:@"distanceFromHome"];
[poiArray replaceObjectAtIndex:i withObject:mutableDict];
[mutableDict release];
}
NSArray *sortDescriptors = [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"distanceFromHome" ascending:YES] autorelease]];
[poiArray sortUsingDescriptors:sortDescriptors];
NSLog (@"poiArray: %@", poiArray);
[homeLocation release];
EDIT: I added this to my code, but it still doesn't work ...
- (void) displayPois {
[mapView removeAnnotations: mapView.annotations];
for(int i = 0; i < 10; i++) {
NSDictionary *poiDict = [poiArray objectAtIndex:nextPoiIndex++];
CLLocationCoordinate2D poiCoordinate;
poiCoordinate.latitude = [[poiDict valueForKey:@"workingCoordinate.latitude"] doubleValue];
poiCoordinate.longitude = [[poiDict valueForKey:@"workingCoordinate.longitude"] doubleValue];
MyHomeAnnotation *poiAnnotation = [[MyHomeAnnotation alloc]
initWithCoordinate:poiCoordinate
title:[poiDict valueForKey:@"Subtitle"]
];
[mapView addAnnotation:poiAnnotation];
[self loadAndSortPOIs];
[poiAnnotation release];
} [self adjustMapZoom];
}
source
share