Showing multiple annotation with user location at center

822 views Asked by At

all I need to show multiple annotations within a mapview and zoom to show all this annotations. I have the code fore that

MKMapRect zoomRect = MKMapRectNull;

int i = 0;
for (Post *post in _allPostsToList) {
    if (((post.location2D.latitude == 0.0f)&&(post.location2D.longitude == 0.0f))||(!CLLocationCoordinate2DIsValid(post.location2D))) {
        i++;
        continue;
    }
    MyAnnotation *annotation = [[MyAnnotation alloc] initWithpost:post];
    annotation.tag = i++;
    [mapView addAnnotation:annotation];

    MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
    MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
    zoomRect = (MKMapRectIsNull(zoomRect))?pointRect:MKMapRectUnion(zoomRect, pointRect);
}
[mapView setVisibleMapRect:zoomRect animated:YES];

it works fine but, I need one more thing with this, Needs user location blue bubble in the center of the map with showing all the above annotation. How to do this. I tried this

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
        MKMapRect zoomRect = mapView.visibleMapRect;
        MKMapPoint annotationPoint = MKMapPointForCoordinate(newLocation.coordinate);
        MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
        zoomRect = (MKMapRectIsNull(zoomRect))?pointRect:MKMapRectUnion(zoomRect, pointRect);
        [mapView setVisibleMapRect:zoomRect animated:YES];
        [manager stopUpdatingLocation];

   }

Its working But its not centering user location How to dow this. Can anyone solve this problem

2

There are 2 answers

0
tiguero On

Just a bet; what about accessing your mapView's region and try to set the new center:

MKCoordinateRegion region = mapView.region;
region.center = newLocation.coordinates;
[mapView setRegion:region animated:YES];
0
Craig On

In didUpdateToLocation you get the current visible Rect (zoomRect), then if it is not null you're joining it with the pointRect and zooming/panning to that. How would that end up centered on the pointRect? It would only happen if the two of them had exactly the same center.

If you want to be centered on the userlocation but show all the points you could get the maximum distance of the points from the userlocation and create a maprect with a center and a span to match. But if the points were all off in one direction and the userlocation is in the middle of the screen, the other side of the screen is wasted.