iPhone MapKit을 사용하여지도 주석에 k-means 클러스터링 알고리즘을 구현하려고합니다. MKAnnotation을 구현하는 2 개의 클래스가 있습니다. 개별 점에 대한 PostLocationAnnotation과 점 클러스터에 대한 LocationGroupAnnotation입니다.NSDictionary에서 NSMutableArray로 항목 추가하기
내 맵뷰 제어기@interface LocationGroupAnnotation : NSObject <MKAnnotation>
{
NSMutableArray *_locations;
CLLocationCoordinate2D _coordinate;
}
@property (nonatomic, retain) NSArray *locations;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
+ (LocationGroupAnnotation *)initWithLocations:(NSArray *)locationArray;
+ (LocationGroupAnnotation *)initWithCoordinate:(CLLocationCoordinate2D)coordinate;
- (id)initWithLocations:(NSArray *)locationArray;
- (id)initWithCoordinate:(CLLocationCoordinate2D)startCoordinate;
- (void)addAnnotation:(PostLocationAnnotation *)annotation;
- (NSUInteger)locationCount;
@end
, I는 위치 각각 랜덤하게 선택한 k 개의 LocationGroupAnnotations를 생성합니다 (initWithCoordinate 방법을 사용)에 의해 LocationGroupAnnotations에 PostLocationAnnotations 모두를 추가하는 방법이 다음과 같이 LocationGroupAnnotation의 헤더는 주석에서 가장 가까운 LocationGroupAnnotations에 PostLocationAnnotations를 추가합니다. 이를 위해, 그래서 같은 ('수단'이 전에 채운 LocationGroupAnnotations의 NSMutableArray를이다)이있는 NSMutableArray NSMutableDictionary의 객체를 사용
// find nearest cluster to each point
NSMutableArray *distances = [[NSMutableArray alloc] initWithCapacity:[[ffMapView annotations] count]];
for (id <MKAnnotation> point in [ffMapView annotations])
{
if ([point isKindOfClass:[PostLocationAnnotation class]])
{
NSMutableDictionary *distanceDict = [[NSMutableDictionary alloc] initWithCapacity:2];
[distanceDict setObject:point forKey:@"location"];
double minDistance = 0;
LocationGroupAnnotation *closestMean = nil;
for (id <MKAnnotation> meanPoint in means)
{
if ([meanPoint isKindOfClass:[LocationGroupAnnotation class]])
{
if (closestMean)
{
if ([ClusteringTools getDistanceBetweenPoint:[point coordinate] and:[meanPoint coordinate]] < minDistance)
{
closestMean = meanPoint;
minDistance = [ClusteringTools getDistanceBetweenPoint:[point coordinate] and:[meanPoint coordinate]];
}
} else {
closestMean = meanPoint;
minDistance = [ClusteringTools getDistanceBetweenPoint:[point coordinate] and:[meanPoint coordinate]];
}
}
}
[distanceDict setObject:closestMean forKey:@"closestMean"];
[distances addObject:distanceDict];
[distanceDict release];
}
}
// add annotations to clusters
for (NSDictionary *entry in distances)
{
[(LocationGroupAnnotation *)[entry objectForKey:@"closestMean"] addAnnotation:[entry objectForKey:@"location"]];
}
I는 데 문제가 언제 I 출력 각 locationCount 이것 이후 LocationGroupAnnotation, 나는 각각에 대해 0을 얻습니다. 나는 주석이 (LocationGroupAnnotation에서)과 같이 추가 될 때마다 로그 출력이 있습니다
- (void)addAnnotation:(PostLocationAnnotation *)annotation
{
[_locations addObject:annotation];
NSLog(@"Added annotation at (%f,%f) to cluster %@",
[annotation coordinate].latitude,
[annotation coordinate].longitude,
[self description]);
}
을 ... 그리고 모든 추가되는 같은 메모리 주소에 의해 판단 곳은해야한다, 그것은 보인다. 무슨 일 이니?
빙고. _locations를 초기화하지 않습니다! – benwad