Wednesday, 23 October 2013

set zoom scale in MapView to fit annotations

In location based application we are displaying annotations in MapView but  to show all annotation on screen we have to fit the zoom scale according to no of annotation and their latitude and longitude,I here apply patch when there are two annotations to fit them proper.

To fit all annotations apply this code:

-(void)zoomToFitMapAnnotations:(MKMapView*)mapView
{
    if([self.annotations count] == 0)
        return;
    
    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;
    
    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;
    
    for(id<MKAnnotation>annotation in self.annotations)
    {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
        
        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }

    MKCoordinateRegion region;
    region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
    region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
    if([self.annotations count]==2){
        region.span.latitudeDelta = 5.0; // Add a little extra space on the sides
            region.span.longitudeDelta =5.0;
    }
    else{
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;
        }
                                  
    
    //fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 0.1; // Add a little extra space on the sides
    
    region = [mapView regionThatFits:region];
    [mapView setRegion:region animated:YES];

}


No comments:

Post a Comment