I have a method that is getting called when someone zooms camera on the map (Google map). I recalculate the positions of markers of map and the code is clunky and not effective. I iterate over arrays three times per method call and that is really slow. When I have 600 markers the performance is really lacking.
What could I improve to make it faster?
I use following local variables:
float lastZoomLevel_; // last zoom value on last zoom
BOOL forceRecalculateMap; // when new data arrives I use this to force repositioning
NSArray *pointsArrayV_; // Array of BankPoint instances, object that holds location and description of marker
- (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position
{
float currentZoomLevel = mapView.camera.zoom;
float diff = fabs(currentZoomLevel - lastZoomLevel_);
if (diff > 0.3 || self.forceRecalculateMap){
self.forceRecalculateMap = NO;
lastZoomLevel_ = currentZoomLevel;
markersGroupArray_ = [[NSMutableArray alloc] init];
for (BankPoint *bpoint in pointsArrayV_) {
CLLocationCoordinate2D coord = bpoint.coordinates.coordinate;
CGPoint currentPoint = [mapView.projection pointForCoordinate:coord];
if ([markersGroupArray_ count] == 0){
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:bpoint, nil];
[markersGroupArray_ addObject:array];
}
else {
BOOL flag_groupadded = NO;
int counter= 0;
for (NSMutableArray *array in markersGroupArray_){
for (BankPoint *bbpoint in array){
CLLocationCoordinate2D mcoord = bbpoint.coordinates.coordinate;
CGPoint mpt = [mapView.projection pointForCoordinate:mcoord];
if ([self distance:mpt point:currentPoint] < 20){
flag_groupadded = YES;
break;
}
}
if (flag_groupadded){
break;
}
counter++;
}
if (flag_groupadded){
if ([markersGroupArray_ count] > counter){
NSMutableArray *groupArray = [markersGroupArray_ objectAtIndex:counter];
[groupArray insertObject:bpoint atIndex:0];
[markersGroupArray_ replaceObjectAtIndex:counter withObject:groupArray];
}
}
else if (!flag_groupadded){
NSMutableArray * array = [[NSMutableArray alloc]initWithObjects:bpoint, nil];
[markersGroupArray_ addObject:array];
}
}
}
[mapView clear];
for (NSArray *array in markersGroupArray_){
BankPoint *item = [array objectAtIndex:0];
CLLocationCoordinate2D coord = item.coordinates.coordinate;
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = coord;
marker.map = mapView;
marker.userData = item;
}
}
}
- (float)distance :(CGPoint)pointA point:(CGPoint) pointB
{
return sqrt( (pow((pointA.x - pointB.x),2) + pow((pointA.y-pointB.y),2)));
}